Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behavior of preg_match for dashes and underscores

I have following two expressions. both are almost same, in first i check the string ending with 3 dashes and in second ending with 3 underscores

$str="this-is_normal-test---";
$str= preg_match("/[a-zA-z0-9]+(-+)$/",$str,$matches);
print_r($matches);

$str="this-is_normal-test___";
$str= preg_match("/[a-zA-z0-9]+(_+)$/",$str,$matches);
print_r($matches);

Here is the output:

Array
(
    [0] => test---
    [1] => ---
)
Array
(
    [0] => test___
    [1] => _
)

The problem is, the first one shows all the three matched dashes and the second one shows only one underscore matched. why? What is the logic/happening for this weird behavior ?

like image 954
Anup_Tripathi Avatar asked Dec 09 '25 03:12

Anup_Tripathi


1 Answers

In US-ASCII (and most derived encodings), the [A-z] range includes _ but not -:

echo implode('', range('A', 'z'));
ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz

I suppose it's a typo and you really mean:

'/[a-z0-9]+(-+)$/i'
like image 169
Álvaro González Avatar answered Dec 10 '25 16:12

Álvaro González



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!