【问题标题】:Find characters in string and make them a link in php [duplicate]在字符串中查找字符并使它们成为php中的链接[重复]
【发布时间】:2019-07-23 21:11:18
【问题描述】:

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

【问题讨论】:

  • 你试过什么?什么没用?你得到了什么?你期待什么?什么不适用于您的代码,它在哪里?
  • 这不是奇怪的代码...这是降价。
  • 我还没有尝试过任何东西。我不擅长正则表达式以及在文本中查找和替换字符串。我想我需要一些正则表达式匹配。

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


【解决方案1】:

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

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

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

然后将其替换为&lt;a href="$2"&gt;$1&lt;/a&gt;。例如:

$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.

【讨论】:

    【解决方案2】:

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

    如果你想使用 PHP 将其转换为 HTML,你可以使用这个库:https://parsedown.org/

    优点是您可以转换帖子中存在的任何其他降价标签和其他形式的降价链接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 2015-10-24
      • 2014-01-15
      • 2015-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多