preg_match意外行为

时间:2015-04-14 11:48:39

标签: php regex preg-match

这是我的代码:

preg_match('/(?<=groups\\/)\\d+/im', $_SERVER['REQUEST_URI'], $matches)

$_SERVER['REQUEST_URI'] = "/groups/S14022/"时,$matches为空。

$_SERVER['REQUEST_URI'] = "/groups/S14022"时,$matches[0]让我“S14022”。

我必须更改正则表达式才能匹配这两种情况?

2 个答案:

答案 0 :(得分:1)

试试这种方式,

$re = "/(?<=\\/groups\\/)S\\d+\\/?/m"; 
$str = "/groups/S14022/\n/groups/S14022"; 

preg_match_all($re, $str, $matches);

enter image description here

参见演示https://regex101.com/r/qP2rO5/1

答案 1 :(得分:0)

我认为你所需要的只是this regex(正如你的正则表达式中,你遗漏了S):

(?<=groups\/)S\d+

PHP代码:

$re = "/(?<=groups\\/)S\\d+/im"; 
$str = "/groups/S14022/\n/groups/S14022"; 
preg_match_all($re, $str, $matches);
print_r($matches);

sample program的输出:

Array
(
    [0] => Array
        (
            [0] => S14022
            [1] => S14022
        )
)