47

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

Could someone please provide a example?

Daniel Blackmore
  • 481
  • 1
  • 5
  • 6
  • What examples have you found that don't work? How do they not work? – BoltClock Jun 22 '11 at 15:13
  • 1
    I will also add that for string manipulation questions of all sorts, it helps to get the right answer if you provide a concrete example or two of what you would have going into the manipulation and what you would like to have coming out of the manipulation. – EBGreen Jun 22 '11 at 15:15

3 Answers3

91

I normally use something like:

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

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

jeroen
  • 91,079
  • 21
  • 114
  • 132
  • 14
    you should use single quotes for regex in PHP `preg_replace('/[^ \w]+/', '', $string)` double quotes with \ in them can result in unexpected behaviour – DarkMukke Jan 26 '13 at 11:09
  • you should say all non-english characters, for example it removes Cyrillic symbols too – Eugene May 20 '18 at 15:57
30
[^0-9a-zA-Z_\s] 

is what you want to replace.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Raffael
  • 19,547
  • 15
  • 82
  • 160
  • 18
    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. – TecBrat Apr 18 '12 at 18:39
  • 1
    `\s` does not mean space always... – Vishal Kumar Sahu Feb 09 '17 at 09:37
8
<?php
$string = 'April 15, 2003';
$pattern = '/[^\w ]+/';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
?>
agent-j
  • 27,335
  • 5
  • 52
  • 79