PHP 将所有 url 转换为 html 链接 [重复]

2024-03-18

可能的重复:
将文本中的 URL 替换为 HTML 链接 https://stackoverflow.com/questions/1188129/replace-urls-in-text-with-html-links

我通过下面的函数传递包含多个 url 的字符串变量,仅通过正确的 HTML 链接才能获得相同的内容。

public function convertUrlsToLinks($text){
    return preg_replace( '@(?<![.*">])\b(?:(?:https?|ftp|file)://|[a-z]\.)[-A-Z0-9+&#/%=~_|$?!:,.]*[A-Z0-9+&#/%=~_|$]@i', '<a href="\0" target="_blank">\0</a>', $text );
}

它根本不起作用。我缺少什么?

代码必须跳过现有链接,<img>'s src价值观(或类似的东西。)


假设你已经有一个 html 文档,我将 URL 的识别限制为

  • 不以“开头
  • 以 http 或 www 开头

我想出了这样的解决方案:

$string = 'lorem ipsum www.foo.bar dolor sit <a href="http://fail.org">http://fail.org</a><img src="www.foo.bar"> amet http://abc.de.fg.com?bar=baz';
$rx = '%[^"](?P<link>(?:https?://|www\.)(?:[-_a-z0-9]+\.)+(?:[a-z]{2,4}|museum/?)(?:[-_a-z0-9/]+)?(?:\?[-_a-z0-9+\%=&]+)?(?!</a)(\W|$))%ui';
echo preg_replace_callback($rx, function($matches) {
    return '<a href="'.$matches['link'].'">'.$matches['link'].'</a>';
}, $string).PHP_EOL;

输出字符串是

lorem ipsum<a href="www.foo.bar ">www.foo.bar </a>dolor sit <a href="http://fail.org">http://fail.org</a><img src="www.foo.bar"> amet<a href="http://abc.de.fg.com?bar=baz">http://abc.de.fg.com?bar=baz</a>

正则表达式should作为意向工作,你的示例字符串可能会有所帮助

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PHP 将所有 url 转换为 html 链接 [重复] 的相关文章

随机推荐