I have this pattern which starts with (?<![\d.,])
and ends with (?![\d.,%]| %)
Why does it match 16
?
I would expect it not to match anything in this string
$pattern = '/(?<![\d.,])-?\d{1,3}(?:(?:[. ]\d{3})*|\d*)(?:\b|[^.,%]|[,]\d{1,2})-?(?![\d.,%]| %)/';
$value = 'dag 08-16 flex pakke';
echo "pattern: $pattern
value: $value
";
preg_match_all($pattern, $value, $matches);
print_r($matches);
Your lookarounds stand next to optional patterns, -?
. Thus, whenever the lookarounds fail, backtracking occurs, and the unwelcome matches occur.
To avoid this, account for the optional pattern inside the lookaround patterns.
/-?(?<![\d.,]-|[\d.,])\d{1,3}(?:(?:[. ]\d{3})*|\d*)(?:\b|[^.,%]|,\d{1,2})(?!-?(?:[\d.,%]| %))-?/
^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^
See the regex demo