Weird PHP Regex Preg_Match Bug?

  php, preg-match, regex

My PHP version is PHP 7.2.24-0ubuntu0.18.04.7 (cli)

I’ve encountered a very weird bug when using preg_match. Can anyone explain it to me?

The first section of code here works, the second one doesn’t. But the regex itself is valid. For some reason the something_happened word is causing it to fail.

$one = ' (branch|leaf)';
echo "ONE:n";
preg_match('/(?:( ?)?((?:(?:**[(?:!?d+)?])***[A-Za-z_]w*)+(?: ?| ?(?:**[(?:!?d+)?])***[A-Za-z_]w*)+)(?: ?))?/', $one, $matches, PREG_OFFSET_CAPTURE);
print_r($matches); // this works

$two = 'something_happened (branch|leaf)';
echo "nTWO:n";
preg_match('/(?:( ?)?((?:(?:**[(?:!?d+)?])***[A-Za-z_]w*)+(?: ?| ?(?:**[(?:!?d+)?])***[A-Za-z_]w*)+)(?: ?))?/', $two, $matches2, PREG_OFFSET_CAPTURE);
print_r($matches2); // this doesn't work

It seems somehow related to the word something_happened. If I change this word it works.

The regex is matching 2 or more type names separated by | that may or may not be surrounded in (), and each type name may or may not be preceded by any number of [] (or [some number] or [!some number]) and *.

Source: Ask PHP

LEAVE A COMMENT