首页 > 解决方案 > 在字符串中查找字符并将它们作为 php 中的链接

问题描述

我在 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

标签: phpregexstringpreg-replacestr-replace

解决方案


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

\[([^]]+)]\((http[^)]+)\)

它查找 a [,然后是一些非]字符、a](http,然后是一些非)字符,直到 a )

然后将其替换为<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);

输出:

This is a blog post hey check out this website <a href="http://www.website.com">Website Name</a>. It is a real good domain.

推荐阅读