从字符串中提取URL [英] Extract URL from string

查看:652
本文介绍了从字符串中提取URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种可靠的解决方案,以从字符串中提取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?

我发现的所有解决方案都适用于某些URL,但不适用于其他URL.

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)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{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)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»""‘’]))

这篇关于从字符串中提取URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆