问题描述
我有这样的文字:
$ string =这是我朋友的网站http://example.com我想它是科尔;
如何将链接提取到另一个变量中?
我知道它应该使用正则表达式,尤其是 preg_match()
但我不知道如何?
可能最安全的方式是使用WordPress的代码片段。下载最新的(当前3.1.1)并查看wp-includes / formatting.php。有一个名为make_clickable的函数,它具有param的纯文本并返回格式化的字符串。您可以抓取代码来提取网址。虽然这很复杂。
这一行正则表达式可能会有所帮助。
preg_match_all('#\bhttps:// [^ \s()<>] +(:\([\w\d] + \)|([^ [: punct:] \s] | /))#',$ string,$ match);
但是这个正则表达式仍然无法删除一些格式不正确的URL(例如 http :// google:ha.ckers.org
)。
另见:
I have this text:
$string = "this is my friend's website http://example.com I think it is coll";
How can I extract the link into another variable?
I know it should be by using regular expression especially preg_match()
but I don't know how?
Probably the safest way is using code snippets from WordPress. Download the latest one (currently 3.1.1) and see wp-includes/formatting.php. There's a function named make_clickable which has plain text for param and returns formatted string. You can grab codes for extracting URLs. It's pretty complex though.
This one line regex might be helpful.
preg_match_all('#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#', $string, $match);
But this regex still can't remove some malformed URLs (ex. http://google:ha.ckers.org
).
See also:How to mimic StackOverflow Auto-Link Behavior
这篇关于在PHP中从文本中提取URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!