【发布时间】:2013-04-27 08:07:51
【问题描述】:
我有一个包含 URL 和其他文本的字符串。我想将所有 URL 放入 $matches 数组中。但是以下代码不会将所有 URL 都放入 $matches 数组中:
$matches = array();
$text = "soundfly.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(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]$i', $text, $matches);
print_r($matches);
上面的代码会得到:
http://tinyurl.com/9uxdwc
http://google.com
http://tinyurl.com/787988
.
但遗漏了以下 4 个网址:
schoollife.edu
hello.net
news.yahoo.com
en.wikipedia.org/wiki/Country_music
你能告诉我一个例子,我怎样才能修改上面的代码来获取所有的 URLs
【问题讨论】:
-
您的正则表达式强制指定 http/https/ftp/file 协议。让它成为可选的。
-
@sevenseacat 我也遇到了类似的问题。你能举一个修改过的正则表达式的例子吗?
-
查看我的更新答案
-
@RakeshSharma 非常感谢您的回复。但是您的答案也会将
some、random作为有效答案。但最初的问题是试图只获取该字符串中的 URL。 ($matches 数组应该只包含网址)。 -
查看我的更新答案希望这是你找到的