使用PHP从字符串中提取URL [英] Extract URL's from a string using PHP

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

问题描述

我们如何使用PHP识别字符串中的URL,并将其存储在数组中?

How can we use PHP to identify URL's in a string and store them in an array?

如果URL包含逗号,则不能使用explode函数,它将无法给出正确的结果.

Cannot use the explode function if the URL contains a comma, it wont give correct results.

推荐答案

REGEX是您的问题的答案.以Object Manipulator的答案为准..它所缺少的就是排除逗号",因此您可以尝试将此代码排除在外,并给出3个单独的URL作为输出:

REGEX is the answer for your problem. Taking the Answer of Object Manipulator.. all it's missing is to exclude "commas", so you can try this code that excludes them and gives 3 separated URL's as output:

$string = "The text you want to filter goes here. http://google.com, https://www.youtube.com/watch?v=K_m7NEDMrV0,https://instagram.com/hellow/";

preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $string, $match);

echo "<pre>";
print_r($match[0]); 
echo "</pre>";

,输出为

Array
(
    [0] => http://google.com
    [1] => https://www.youtube.com/watch?v=K_m7NEDMrV0
    [2] => https://instagram.com/hellow/
)

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

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