Reputation: 21386
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?
Upvotes: 2
Views: 563
Reputation: 26380
Replace '/[^[:alpha:]]+/'
with '/[^[:alpha:][:digit:]]+/'
. The original is replacing anything that's not an alphabetic character. Adding [:digit:] means it will replace anything that's not a letter or a number, so your numbers will be preserved as well.
Upvotes: 2
Reputation: 15706
Your third pattern, /[^[:alpha:]]+/
is replacing everything that's not a letter with an underscore. So add numbers to it, like /[^[:alpha:]0-9]+/
Upvotes: 5