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);
?>
Share:
76,814
Daniel Blackmore
Author by

Daniel Blackmore

Updated on July 09, 2022

Comments

  • Daniel Blackmore
    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
    TecBrat about 12 years
    This 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
    DarkMukke over 11 years
    you 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
    Vishal Kumar Sahu over 7 years
    \s does not mean space always...
  • Eugene
    Eugene about 6 years
    you should say all non-english characters, for example it removes Cyrillic symbols too