How to replace all special characters except underscore and period in php?

Can someone show me how I can replace all special characters in a string except underscores and period characters. And also I was trying to figure out how to do this in order to replace the templates that read the PHP manual and it is so confusing for a beginner like me, is there any other documentation or tutorial that is simplified for beginners, so I do not need to publish yet one such question and bother people every time I want to use this feature?

 preg_replace('/[^a-zA-Z0-9]/', '', $string); 

this is what I replace with all special characters, but I want except _ and . .

+6
source share
2 answers

Put _ and . into a negative character set ( [^...] ):

 $string = preg_replace('/[^a-zA-Z0-9_.]/', '', $string); 

You cannot skip $string = .. because preg_replace returns the replaced string. It does not change the string in place.

+13
source

You can use some php filter widget such as a cleaner (to set a whitelist for input) ...

But still, we would like to invite you to study the regular expression!

+1
source

All Articles