在字符串中查找字符并使它们成为 php 中的 link
Find characters in string and make them a link in 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
您可以将 preg_replace
与此正则表达式一起使用:
\[([^]]+)]\((http[^)]+)\)
它寻找一个 [
,然后是一些非 ]
字符,一个 ]
和 (http
,然后是一些非 )
字符直到 )
。
然后替换为 <a href=""></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=""></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.
这个奇怪的代码是 Markdown(例如在 SO 中使用)。
如果您想使用 PHP 将其转换为 HTML,您可以使用此库:https://parsedown.org/
优点是您可以转换帖子中出现的任何其他降价标签和其他形式的降价链接。
我在 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
您可以将 preg_replace
与此正则表达式一起使用:
\[([^]]+)]\((http[^)]+)\)
它寻找一个 [
,然后是一些非 ]
字符,一个 ]
和 (http
,然后是一些非 )
字符直到 )
。
然后替换为 <a href=""></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=""></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.
这个奇怪的代码是 Markdown(例如在 SO 中使用)。
如果您想使用 PHP 将其转换为 HTML,您可以使用此库:https://parsedown.org/
优点是您可以转换帖子中出现的任何其他降价标签和其他形式的降价链接。