Replace all characters except letters, numbers, spaces and underscores

Daniel Blackmore picture Daniel Blackmore · Jun 22, 2011 · Viewed 72.1k times · Source

I am looking to replace all characters in a string except letters, numbers, spaces and underscores.

Could someone please provide a example?

Answer

jeroen picture jeroen · Jun 22, 2011

I normally use something like:

$string = preg_replace("/[^ \w]+/", "", $string);

That replaces all non-space and non-word characters with nothing.