【问题标题】:Find and Replace SQL Query with Regex使用正则表达式查找和替换 SQL 查询
【发布时间】:2020-03-06 17:32:50
【问题描述】:

我在数据库中有一些这样的链接:

<a href="https://example.com/full/?api=0aca610f4a9983fc1fa30brs6c302f970ae87c29da&amp;url=aHR0cHM6Ly93d3c0Mi56aXBwfseXNoYXJlLmNvbS92L1IwVlNwZkk4L2ZpbGUuaHRtbA==&amp;type=2" target="_blank" rel="noreferrer noopener">www.example.net/v/R0V82dSpfI8/file.html</a>

<a href="https://example.com/full/?api=sd4a5sdf540c1fa30b6c302f9704a6sadf&amp;url=asdfa54asd5fa5sdfa8dRcFFcafasdf==&amp;type=2" target="_blank" rel="noreferrer noopener">example.org/000hcwoc0kcwy1/545da45a.rar.html</a>

我需要一个“查找和替换”SQL 查询,它将 找到锚文本,添加 https:// 并将其放在 href 标记中。

基于第二个示例,最终的 HTML 应该是这样的:

<a href="https://example.org/000hcwoc0kcwy1/545da45a.rar.html" target="_blank" rel="noreferrer noopener">example.org/000hcwoc0kcwy1/545da45a.rar.html</a>

我并不完全是一名开发人员,我真的很讨厌正则表达式,因为我不懂它。你能帮我解决这个问题吗?

【问题讨论】:

  • 您使用的是什么版本的 MySQL? regexp_replace() 仅从 MySQL 8+ 开始可用。什么是“锚文本”?什么是“href 标签”
  • Debuggex Demo 等在线正则表达式调试工具有助于直观地调试正则表达式。
  • @TARIK SUCU ,这些值是否在表格的单个列中可用?
  • Gordon : 服务器版本: 10.3.20-MariaDB MariaDB 服务器它的支持 Danblack : 我会试试 Arun : 是的,它是 wordpress 表并且 html 位于 post 表的内容列中

标签: php mysql sql regex


【解决方案1】:

您可以使用正则表达式函数来做到这一点,虽然它有点复杂,因为 MySQL/MariaDB 不支持捕获组。

您可以识别字符串中需要替换为正则表达式'href="[^"]+"'的部分。

另一方面,您可以使用'&gt;[^&lt;]+' 捕获目标网址(这意味着:'&gt;' 之后的所有字符,直到遇到'&lt;')。所以这给了你替换字符串:

substring(regexp_substr(link, '>[^<]+') from 2)

最终表达:

regexp_replace(
    link, 
    'href="[^"]+"',
    concat('hef="https://', substring(regexp_substr(link, '>[^<]+') from 2), '"')
)

Demo on DB Fiddle

原始数据:

select link from mytable;
|链接 | | :------------------------------------------------ -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------- | | www.example.net/v /R0V82dSpfI8/file.html | | example.org/000hcwoc0kcwy1/545da45a .rar.html |

查询:

select 
    regexp_replace(
        link, 
        'href="[^"]+"',
        concat('hef="https://', substring(regexp_substr(link, '>[^<]+') from 2), '"')
    ) new_link
from mytable
|新链接 | | :------------------------------------------------ -------------------------------------------------- -------------------------------------------------- -- | | www.example.net/v/R0V82dSpfI8/file.html一个> | | example.org/000hcwoc0kcwy1/545da45a.rar.html |

【讨论】:

  • 非常感谢您的时间和精力。它的工作,但我需要“喜欢”运营商。因为这个链接是 html 的一部分(我的意思是,链接在 wp_posts 表的内容列中) wp_post 表 PostID ----- PostContent 1 ---

    lorem ipsum dolor sit amet example.com/asdladsasadla">example.net/asdfasdfas</a > lorem ipsum dolor sit

    ....
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-06
相关资源
最近更新 更多