问题描述
我正在尝试找到一种可靠的解决方案来从字符串中提取 url.我有一个网站,用户可以在其中回答问题,在源框中输入信息来源,我允许他们输入 url.我想提取该网址并将其设为超链接.类似于 Yahoo Answers 的做法.
I'm trying to find a reliable solution to extract a url from a string of characters. I have a site where users answer questions and in the source box, where they enter their source of information, I allow them to enter a url. I want to extract that url and make it a hyperlink. Similar to how Yahoo Answers does it.
有人知道可以做到这一点的可靠解决方案吗?
Does anyone know a reliable solution that can do this?
我发现的所有解决方案都适用于某些网址,但不适用于其他网址.
All the solutions I have found work for some URL's but not for others.
谢谢
推荐答案
John Gruber 花费了相当多的时间时间完善链接检测的一个正则表达式来统治所有".使用其他答案中提到的 preg_replace()
,使用以下正则表达式应该是最准确(如果不是最准确)检测链接的方法之一:
John Gruber has spent a fair amount of time perfecting the "one regex to rule them all" for link detection. Using preg_replace()
as mentioned in the other answers, using the following regex should be one of the most accurate, if not the most accurate, method for detecting a link:
(?i)((?:[a-z][w-]+:(?:/{1,3}|[a-z0-9%])|wwwd{0,3}[.]|[a-z0-9.-]+[.][a-z]{2,4}/)(?:[^s()<>]+|(([^s()<>]+|(([^s()<>]+)))*))+(?:(([^s()<>]+|(([^s()<>]+)))*)|[^s`!()[]{};:'".,<>?«»""‘’]))
如果您只想匹配 HTTP/HTTPS:
If you only wanted to match HTTP/HTTPS:
(?i)((?:https?://|wwwd{0,3}[.]|[a-z0-9.-]+[.][a-z]{2,4}/)(?:[^s()<>]+|(([^s()<>]+|(([^s()<>]+)))*))+(?:(([^s()<>]+|(([^s()<>]+)))*)|[^s`!()[]{};:'".,<>?«»""‘’]))
这篇关于从字符串中提取 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!