I have a PHP variable, say
$myvariable = "te [email protected] na#@)(me+=&t^*ext?>;.'na^%me";
I want to replace special characters and group of special characters including blank space with a single underscore
_. The string may contain
& and it may be replaced with
The result of previous variable should be;
How can I do this in PHP?
This assumes, anything but "characters" is regarded disposable.
$patterns = array( '/&/' => 'and', // Ampersand to "and" '/[^[:alpha:]]+/' => '_' // Anything *but* a character to underscore ); $result = preg_replace(array_keys($patterns), array_values($patterns), $input);
The last pattern replaces groups of one or more occurences of "non-word" characters according to the current locale1 (and thus including white-space).
1 Side-note (might be irrelevant): if the server the script runs on has
en_US as locale, the following replacements occur:
$input = 'app!le___s &! orän=%ges'; $result = 'app_le_s_and_or_n_ges';
If the locale is
de_DE, this would be the result:
$result = 'app_le_s_and_orän_ges';
ä is part of
[[:alpha:]] in this particular locale. The obvious solution to circumvent this would be to substitute the character class for
this should do it:
$myvariable = str_replace('&','and',$myvariable) $myvariable = preg_replace ('/[^a-z]+/i', '_' , $myvariable)
the caret (^) inside the squared brackets means to look for everything, that is not declared in the brackets. So every special character is not "a-z". The plus signalises, that multiple occurences should be matched. The 'i' behind the delimiting slash means to do a case-insensitive search.