对带有查询字符串的URL使用preg_match

Using preg_match on a URL with a query string

本文关键字:使用 preg match URL 查询 字符串      更新时间:2023-09-26

我想找到与给定URL匹配的所有URL。

当我用这个URL尝试下面的代码时:

$url_regex = '^http://toilatester.com/category/?xv=.*'; 
$urls = array( 
    'http://toilatester.com/category/?xv=123333/time1-one1', 
    'http://toilatester.com/category/?xv=78787878/time1-one1', 
    'http://toilatester.com/category/?xv=78547547/time1-one1' 
);
foreach ($urls as $urllink) { 
    if (preg_match($url_regex, $urllink, $a)) { 
        $arr_link[] = $a[0]; 
    } 
} 
die(print_r($arr_link)); 

它与预期不匹配。

如果我将$url_regex更改为^http://toilatester.com/category/.*那么它就起作用了,但我需要从http://toilatester.com/category/?xv=开始。

我认为问题出在特殊的字符

请帮忙?感谢

是的,字符在正则表达式中具有特殊含义。要匹配问号,您需要在正则表达式中转义,如:

$url_regex = '^http://toilatester.com/category/'?xv=.*';