查找字符串中的字符,并使其成为php中的链接

时间:2019-03-01 19:46:08

标签: php regex string preg-replace str-replace

我在Wordpress中有1000篇帖子,其中的正文中有超链接的怪异代码。例如,我要查找此的所有实例:

[Website Name](http://www.website.com)

并将其变成

<a href="http://www.website.com">Website Name</a>

在php中实现此目标的最佳方法是什么?

$string = "This is a blog post hey check out this website [Website Name](http://www.website.com). It is a real good domain.
// do some magic

2 个答案:

答案 0 :(得分:3)

您可以在此正则表达式中使用preg_replace

<text>

它将寻找一个\[([^]]+)]\((http[^)]+)\) ,然后是一些非[字符,一个]],然后是一些非(http字符,直到出现)

然后将其替换为)。例如:

<a href="$2">$1</a>

输出:

$string = "This is a blog post hey check out this website [Website Name](http://www.website.com). It is a real good domain.";
echo preg_replace('/\[([^]]+)]\((http[^)]+)\)/', '<a href="$2">$1</a>', $string);

答案 1 :(得分:0)

这个奇怪的代码是Markdown(例如,在SO中使用)。

如果您想使用PHP将其转换为HTML,则可以使用以下库:https://parsedown.org/

好处是您将转换帖子中存在的任何其他markdown标签和其他形式的markdown链接。