Search code examples
phpregexpreg-replacephp-5.3

PHP preg_replace replacing numbers along with special chars


I have the following PHP code to remove special characters from a variable;

<?php
$name = "my%^$@#name8";
$patterns = array( '/\s+/' => '_', '/&/' => 'and', '/[^[:alpha:]]+/' => '_');
$name2 = preg_replace(array_keys($patterns), array_values($patterns), trim($name));
echo $name2;
?>

But, along with special chars, numbers also are getting replaced with underscores_. I want to include numbers in the result. How can I fix this?


Solution

  • Your third pattern, /[^[:alpha:]]+/ is replacing everything that's not a letter with an underscore. So add numbers to it, like /[^[:alpha:]0-9]+/