Preg_replace does not replace underscore

I want to allow only alphanumeric characters and spaces, so I use the following:

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

However, this allows you to emphasize "_", which I do not want. Why is this and how to fix it?

thanks

+4
source share
2 answers

Character class range for the character range between two code points. The _ character is included in the Az range, and you can see this by looking at the ASCII table:

  ... YZ [\] ^ _ `ab ...

Thus, this is not only the underscore that is skipped, but also the other characters that you see above, as indicated in the documentation :

Ranges work in an ASCII sort sequence .... For example, [Wc] equivalent to [][\^_ ` wxyzabc] .

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

 $name = preg_replace('/[^a-z0-9 ]/i', '', $str); 
+1
source

You have a mistake in your expression. The last Z must be capital.

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

Source: https://habr.com/ru/post/1485708/


All Articles