使用正则表达式将内容中的链接替换为超链接



我有一个字符串,其中包含用户的博客内容。如果包括以下内容:

www.google.com
http://google.com
http://www.google.com

在他们的博客文章中,我希望PHP用一个真正的超链接替换这些出现的内容,但保留原始的子字符串(即不将www.google.com更改为http://www.google.com)。

有人知道我如何使用PHP和正则表达式吗?我试过这个:

echo preg_replace('/((www|http://)[^ ]+)/', '<a href="$1" target="_blank">$1</a>', $content);

但是,只有当您用空格结束链接时,才能成功。如果以逗号或句号结束,则失败。

preg_replace('/b(?:(http(s?)://)|(?=www.))(S+)/is',
             '<a href="http$2://$3" target="_blank">$1$3</a>',
             $content); 
$pattern = '/<a (.*?)href=["'](.*?)//(.*?)["'](.*?)>(.*?)</a>/i';
$new_content = preg_replace($pattern, '$5', $content);

最新更新