首页 > 解决方案 > 是否可以在 Mysql 中替换链接并将其设为空白?

问题描述

我有一个名为 description 的数据库表列,在此列中大约有 1000 行。每行可以包含多个链接。例如:

Some description text
<a href="example11.com">Example 11</a>
description text is continue
<a href="example22.com">Example 22</a>
more description text

我可以更新所有链接并添加目标空白吗?在此示例中,文本应更改为:

Some description text
<a href="example11.com" target="_blank">Example 11</a>
description text is continue
<a href="example22.com" target="_blank">Example 22</a>
more description text

摘要是要更改链接并添加目标空白。

<a href="example11.com">Example 11</a> 

<a href="example11.com" target="_blank">Example 11</a>

标签: mysqlsqlmariadb

解决方案


您可以使用该REPLACE功能将一段文本替换为另一段文本。

例如,以下内容将替换<a hrefwith的所有实例<a target="_blank" href

REPLACE(myField, '<a href', '<a target="_blank" href');

在您在问题中提供的文本上使用上述内容将输出以下内容:

Some description text
<a target="_blank" href="example11.com">Example 11</a>
description text is continue
<a target="_blank" href="example22.com">Example 22</a>
more description text

当然,target="_blank"不必遵循href,因此这是完全有效的 HTML。

然而,这并不是一个完美的解决方案。如果锚标签的布局不完全一样<a href(即双空格,其他东西而不是href直接在 之后a),那么这将不起作用。

要更新您的数据,只需使用一个简单的UPDATE语句REPLACE

UPDATE  MyTable
   SET  myField = REPLACE(myField, '<a href', '<a target="_blank" href');

工作小提琴显示了一个简单的案例。


推荐阅读