Replace all characters except letters, numbers, spaces and underscores
76,814
Solution 1
I normally use something like:
$string = preg_replace("/[^ \w]+/", "", $string);
That replaces all non-space and non-word characters with nothing.
Solution 2
[^0-9a-zA-Z_\s]
is what you want to replace.
Solution 3
<?php
$string = 'April 15, 2003';
$pattern = '/[^\w ]+/';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
?>
Author by
Daniel Blackmore
Updated on July 09, 2022Comments
-
Daniel Blackmore almost 2 years
I am looking to replace all characters in a string except letters, numbers, spaces and underscores.
Could someone please provide a example?
-
TecBrat about 12 yearsThis one helped me on a similar issue. Thanks! (For others reading this, don't forget to wrap it in slashes like this:
$new_string=preg_replace('/[^0-9a-zA-Z_]/',"",$old_string)
I took out the \s because I didn't need to allow spaces. -
DarkMukke over 11 yearsyou should use single quotes for regex in PHP
preg_replace('/[^ \w]+/', '', $string)
double quotes with \ in them can result in unexpected behaviour -
Vishal Kumar Sahu over 7 years
\s
does not mean space always... -
Eugene about 6 yearsyou should say all non-english characters, for example it removes Cyrillic symbols too