从 PHP 文本中提取 URL [英] Extract URLs from text in PHP

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

问题描述

我有这样的文字:

$string = "this is my friend's website http://example.com I think it is coll";

如何将链接提取到另一个变量中?

How can I extract the link into another variable?

我知道应该使用正则表达式,尤其是 preg_match() 但我不知道如何?

I know it should be by using regular expression especially preg_match() but I don't know how?

推荐答案

可能最安全的方法是使用 WordPress 的代码片段.下载最新的(目前是 3.1.1)并查看 wp-includes/formatting.php.有一个名为 make_clickable 的函数,它具有 param 的纯文本并返回格式化的字符串.您可以抓取用于提取 URL 的代码.不过还是挺复杂的.

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('#https?://[^s()<>]+(?:([wd]+)|([^[:punct:]s]|/))#', $string, $match);

但是这个正则表达式仍然无法删除一些格式错误的 URL(例如 http://google:ha.ckers.org ).

But this regex still can't remove some malformed URLs (ex. http://google:ha.ckers.org ).

另见:如何模仿 StackOverflow 自动链接行为

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

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