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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With