使用 php 查找文本中的所有 url(链接)
我有这个代码正则表达式,它应该将各种不同的网址转换为某些文本中的链接。
preg_replace 代码是:
$regex = '@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@';
$text = preg_replace($regex, '<a href="$1">$1</a>', $item);
现在它适用于几乎所有你能想象到的 URL,但我遇到的问题是逗号和 URL 中的特殊字符...
问题使我:
http://www.sdfsdfsdf.sd/si/391 ,1000,1/more.html
http://sdfsddsdf-sdfsdfds.sr/组件/选项,com_contact/Itemid,3/lang,si/
有趣的是,在 stackoverflow 上,这两个都可以:)
谢谢,最诚挚的问候,
I have this code regex, which should transform all kind of diffrent urls into links in some text.
The preg_replace code is:
$regex = '@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@';
$text = preg_replace($regex, '<a href="$1">$1</a>', $item);
now it works for almost all URLs you can imagine, but the problems i have are commas, and special characters in URLs...
The problem is making me:
http://www.sdfsdfsdf.sd/si/391,1000,1/more.html
http://sdfsddsdf-sdfsdfds.sr/component/option,com_contact/Itemid,3/lang,si/
Funny here at stackoverflow those two are OK :)
Thanks, best regards,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你必须稍微编辑你的正则表达式。这将完成这项工作:
如您所见,这里添加了一个逗号
[-\w/_\.\,]
,仅此而已。享受!
You have to edit your regex a bit. This will do the job:
As you can see, there's a comma added here
[-\w/_\.\,]
and nothing more.Enjoy!
尝试使用以下函数:
在这里找到它:如何用链接替换普通 URL?
Try using the following function:
Found it here: How to replace plain URLs with links?
您可以使用此库 https://github.com/mxkh/url-finder 进行简单查找HTML 页面或文本中的 URL。我使用 Composer 安装
composer require mxkh/url-finder
此外,该库还支持从流行的视频服务(例如 Youtube、Vimeo)查找视频链接。
我希望这对某人有帮助。
You can use this lib https://github.com/mxkh/url-finder for simple finding URLs in HTML page or in text. Iinstall with composer
composer require mxkh/url-finder
Also this lib has a support for finding video links from popular video services sach as Youtube, Vimeo.
I hope this is helpful to someone.