【问题标题】:How to get URLs from a text string?如何从文本字符串中获取 URL?
【发布时间】: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 非常感谢您的回复。但是您的答案也会将somerandom 作为有效答案。但最初的问题是试图只获取该字符串中的 URL。 ($matches 数组应该只包含网址)。
  • 查看我的更新答案希望这是你找到的

标签: php string text


【解决方案1】:

这是你需要的吗?

$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);

我将协议部分设为可选,添加使用一个点分隔域和 TLD 和一个“+”以获取该点之后的完整字符串(TLD + 额外信息)

结果是:

[0] => soundfly.us 
[1] => schoollife.edu 
[2] => hello.net 
[3] => news.yahoo.com 
[4] => http://tinyurl.com/9uxdwc 
[5] => http://google.com 
[6] => http://tinyurl.com/787988 
[7] => en.wikipedia.org/wiki/Country_music

也适用于 IP 地址,因为必须包含点。用字符串“192.168.0.1”和“192.168.0.1/test/index.php”测试

【讨论】:

    猜你喜欢
    • 2012-02-11
    • 2011-11-17
    • 2015-08-06
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 2013-11-07
    • 1970-01-01
    • 2011-07-30
    相关资源
    最近更新 更多