2013-04-27 69 views
1

我有一个包含URL和其他文本的字符串。我想将所有的URL都存入$matches数组中。但是,下面的代码将无法获得全部的URL中$matches阵列:从字符串中获取所有网址?

$matches = array(); 
$text = "words cotry.lk and newe.com joemiller.us schoollife.edu hello.net some random news.yahoo.com text http://tinyurl.com/9uxdwc some http://google.com random text http://tinyurl.com/787988 and others will en.wikipedia.org/wiki/Country_music URL"; 

preg_match_all('$\b[-A-Z0-9+&@#/%?=~_|!:,.;][.]*[-A-Z0-9+&@#/%=~_|(https?|ftp|file)://-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%?=~_|!:,.;]{8,50}$i', $text, $matches); 
print_r($matches); 

上面的代码不会告诉我以下网址:

cotry.lk 
newe.com 

你能告诉我一个例子,如何我可以修改上面的代码来获取所有的URL。

请注意,并非所有的URL都包含herf,并且这个字符串不是从html文件中获取的。

+0

对于您的情况,您的正则表达式只匹配网址,因为它们的长度 - 它也匹配长度超过8个字符的任何其他单词 – 2013-04-27 12:29:50

回答

2
import re 
def getall_urls(value): 
    pattern = '((?:[\w\d]+\:\/\/)?(?:[\w\-\d]+\.)+[\w\-\d]+(?:\/[\w\-\d]+)*(?:\/|\.[\w\-\d]+)?(?:\?[\w\-\d]+\=[\w\-\d]+\&?)?(?:\#[\w\-\d]*)?)' 
    # Place matches into list (a.k.a array) 
    getall = re.findall(pattern, value) # preg_match_all() function in PHP 
    # Remove duplicates and return the result 
    return set(getall) if getall else() 

这里是Python代码,做的正是你所需要的。表达最初是在互联网上发现和修改的。尽管这段代码是用Python编写的,但您也可以在PHP中轻松使用表达式。

+0

非常感谢您向我解释细节。该正则表达式运行良好。感谢你的帮助。 – 2013-04-27 13:05:39

1

如果我是你,我不会使用preg_match_all,如果你想检查字符串的有效地址。相反,我会将字符串切成单词并使其变得艰难。

filter_var($url, FILTER_VALIDATE_URL) 

如果返回true,你知道它是一个有效的URL

+0

谢谢您的回复。使用您的建议,我只能获得以http://开头的网址。诸如schoollife.edu等其他网址将被忽略。 – 2013-04-27 13:01:22