Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_replace not replacing underscore

I want to allow only alpha numeric characters and spaces, so I use the following;

$name = preg_replace('/[^a-zA-z0-9 ]/', '', $str);

However, that is allowing underscores "_" which I don't want. Why is this and how do I fix it?

Thanks

like image 326
Ally Avatar asked Nov 12 '22 03:11

Ally


1 Answers

The character class range is for a range of characters between two code points. The character _ is included in the range A-z, and you can see this by looking at the ASCII table:

... Y Z [ \ ] ^ _ ` a b ...

So it's not only the underscore that's being let through, but those other characters you see above, as stated in the documentation:

Ranges operate in ASCII collating sequence. ... For example, [W-c] is equivalent to [][\^_`wxyzabc].

To prevent this from happening, you can perform a case insensitive match with a single character range in your character class:

$name = preg_replace('/[^a-z0-9 ]/i', '', $str);
like image 67
Tim Cooper Avatar answered Nov 14 '22 22:11

Tim Cooper