【问题标题】:Regular Expression to extract a url included in a string [duplicate]正则表达式提取字符串中包含的 url [重复]
【发布时间】:2012-12-18 23:03:04
【问题描述】:

可能重复:
How to match URIs in text?
What is the best regular expression to check if a string is a valid URL?

我需要使用正则表达式 (PHP) 从包含许多 URL 的字符串中提取 zip 文件的 URL。

一个简单的例子应该会有所帮助:

目标:提取urlhttp://en.wikipedia.org/wiki/Kettle.zip

基本字符串:

/url?q=http://en.wikipedia.org/wiki/Kettle.zip&sa=U&ei=VpnIUP22Js blah /url?q=http://en.wikipedia.org/wiki/Kettle&sa=U&ei=VpnIUP22Js blah /url?q=http://en.wikipedia.org/wiki/Kettle.rar&sa=U&ei=VpnIUP22Js

更新; 假设基本字符串是

href="http://en.wikipedia.org/wiki/Kettle.zip">一些文字 /a>这里有一些其他文字 a href="http://google.com/wiki/Kettle"> /一个>

我需要提取 http://en.wikipedia.org/wiki/Kettle.zip

任何方法都可以...正则表达式与否。

【问题讨论】:

  • 或其他许多谈论如何使该可点击的人之一,我敢打赌,在所有这些重复的 QA 材料中都有很多正则表达式。
  • 你不能拆分" blah ",解析URL查询字符串(和decodeURI!),获取q参数然后过滤.zip扩展?
  • 如果所有内容都是“url then description”的形式,用空格分隔,然后忘记正则表达式并使用拆分函数,您无需识别它是否是 url因为你有位置...... 然后你可以从查询字符串中解析url主机和路径。

标签: php regex url


【解决方案1】:

不要使用正则表达式。正则表达式不是解决所有与字符串相关的问题的魔杖。

使用parse_url() 拆分您的网址,然后使用explode 拆分& 上的查询字符串。

$url = "http://example.com/url?q=http://en.wikipedia.org/wiki/Kettle.zip&sa=U&ei=VpnIUP22Js";
$query = parse_url($url, PHP_URL_QUERY);
print "query is: $query\n";
$args = explode( '&', $query );
print_r( $args );

运行此命令:

query is: q=http://en.wikipedia.org/wiki/Kettle.zip&sa=U&ei=VpnIUP22Js
Array
(
    [0] => q=http://en.wikipedia.org/wiki/Kettle.zip
    [1] => sa=U
    [2] => ei=VpnIUP22Js 
)

从那里遍历数组并找到您想要的。

【讨论】:

  • “正则表达式不是解决所有与字符串相关的问题的魔杖。”为此 +1。
  • @Iain:去阅读我的发帖历史。在过去的几周里,我一直在敲鼓。 :-)
猜你喜欢
  • 1970-01-01
  • 2020-04-22
  • 1970-01-01
  • 1970-01-01
  • 2015-10-30
  • 2020-08-25
  • 2019-10-07
  • 2011-07-24
  • 2010-10-17
相关资源
最近更新 更多