0

我在使用正则表达式从字符串中检索 URL 参数时遇到问题:

一个示例字符串可能是

some text and http://google.com/?something=this&tag=yahoo.com and more text,我希望能够从中找到yahoo.com

需要注意的是,我需要确保字符串以 开头http://google.com,而不仅仅是搜索&tag=(.*)

preg_match("/google\.com\/.*&tag=(.*) $/", $subject, $matches)

我希望这匹配任何内容,google.com后跟任何内容,然后&tag=是空格。最终目标是解析出URL中的所有tag=值。google.com

有没有更好的方法来实现这一点?

更新:

所以我有这个新的正则表达式:/google\.com\/.*(tag=.*)/但我不确定如何让它在 URL 后面的空格处结束

4

2 回答 2

4

对功能友好parse_url()

$pieces = parse_url('some text http://google.com/?something=this&tag=yahoo.com and whatever');
$query = explode('&', $pieces['query']);

parse_str($pieces['query'], $get);
array_walk($get, function(&$item){
    if (!$sp = strpos($item, ' ')) return;
    $item = substr($item, 0, $sp);
});

var_dump($get); // woo!

编辑:感谢乔纳森的parse_str()功能。

于 2013-08-07T22:28:45.227 回答
1

如果您想获得 的值,tag那么以下正则表达式将完成这项工作:

$string = 'some text and http://google.com/?something=this&tag=yahoo.com
and more text
http://google.com/?something=this&tag=yahoo2.com&param=test
';
preg_match_all('#http://google.com\S+&tag=([^\s&]+)#', $string, $m);
print_r($m[1]);

输出

Array
(
    [0] => yahoo.com
    [1] => yahoo2.com
)

解释

  • http://google.com: 匹配http://google.com
  • \S+: 匹配非空格一次或多次
  • &tag=: 匹配&tag=
  • ([^\s&]+): 匹配除空格和&一次或多次以外的任何内容并将其分组

如果需要,您甚至可以添加s?afterhttp以考虑https,或添加i修饰符以匹配不区分大小写。

于 2013-08-07T22:38:05.733 回答