Raphael Jeger
Raphael Jeger

Reputation: 5232

preg_match unexpected behaviour

This is my code:

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

When $_SERVER['REQUEST_URI'] = "/groups/S14022/", $matches is empty.

When $_SERVER['REQUEST_URI'] = "/groups/S14022", $matches[0] gets me "S14022".

What do I have to change on the regex to match both cases?

Upvotes: 0

Views: 85

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626893

I think all you need is this regex (as in your regex, you are missing S):

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

PHP code:

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

Output of the sample program:

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

Upvotes: 0

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

Try this way,

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

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

enter image description here

See Demo https://regex101.com/r/qP2rO5/1

Upvotes: 1

Related Questions