0

So i need preg_replace() to

  • remove all characters but a-z A-Z 1-9
  • replace spaces with single underscore \s+
  • if there's multiple underscores in string it need to be replaced with single one [_]+

Code

$str = "Hz!!    zÒ142______23 4";
$str = preg_replace('/[^a-zA-Z0-9][_]+\s+/', '_', $str);
echo $str; //Outputs: Hz_z142_23_4

Edit i'd like to do it with single preg_replace

Roman Toasov
  • 747
  • 11
  • 36

1 Answers1

4

You can do it in two replacements:

$str = preg_replace('/[^\w\s]+/', '', $str);
$str = preg_replace('/[^a-zA-Z0-9]+/', '_', $str);

Or, as in comments, you can combine them into one:

preg_replace(array('/[^\w\s]+/', '/[^a-zA-Z0-9]+/'), array('', '_'), $str);
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525