Delete all but valid characters

Valid characters include the alphabet (abcd ..), numbers (0123456789), spaces, "and".

I need to remove any other characters from a string in PHP.

Thanks:)

+6
php regex
source share
2 answers

You can do it:

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

Here the character class [^a-z0-9 "'] will correspond to any character except the ones listed (note the inversion ^ at the beginning of the character class), which are then replaced by an empty string.

+24
source share

Gumbo's answer is correct for your specific specification. But if your "specification" is only "symbolic", then in the end you may need the following:

 $str = preg_replace('{ [^ \w \s \' " ] }x', '', $str ); 

[^ ] : negative character class (everything except inside)

\w : alphanumeric (letters and numbers)

\s : space

\' :'

+1
source share

All Articles