Reputation: 955
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
Upvotes: 5
Views: 1927
Reputation: 15464
You have mistake in your expression. Last Z must be capital.
$name = preg_replace('/[^a-zA-Z0-9 ]/', '', $str);
^
Upvotes: 0
Reputation:
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);
Upvotes: 1