使用php查找文本中的所有网址(链接)

2022-01-02 00:00:00 text url hyperlink php preg-replace

我有这个代码正则表达式,它应该将各种不同的网址转换为某些文本中的链接.

I have this code regex, which should transform all kind of diffrent urls into links in some text.

preg_replace 代码是:

The preg_replace code is:

$regex = '@((https?://)?([-w]+.[-w.]+)+w(:d+)?(/([-w/_.]*(?S+)?)?)*)@';
$text = preg_replace($regex, '<a href="$1">$1</a>', $item);

现在它几乎适用于您可以想象的所有 URL,但我遇到的问题是逗号和 URL 中的特殊字符...

now it works for almost all URLs you can imagine, but the problems i have are commas, and special characters in URLs...

问题让我:

http://www.sdfsdfsdf.sd/si/391,1000,1/more.html

http://sdfsddsdf-sdfsdfds.sr/组件/选项,com_contact/Itemid,3/lang,si/

在 stackoverflow 上很有趣,这两个都可以:)

Funny here at stackoverflow those two are OK :)

谢谢,最好的问候,

推荐答案

您必须稍微编辑一下正则表达式.这将完成这项工作:

You have to edit your regex a bit. This will do the job:

$regex = '@((https?://)?([-w]+.[-w.]+)+w(:d+)?(/([-w/_.,]*(?S+)?)?)*)@';

如您所见,此处添加了一个逗号 [-w/_.,] 仅此而已.

As you can see, there's a comma added here [-w/_.,] and nothing more.

享受吧!

相关文章