I have a PHP variable, say
$myvariable = "te xt!@ 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 and.
The result of previous variable should be;
te_xt_na_me_andt_ext_na_me
How can I do this in PHP?
This assumes, anything but “characters” is regarded disposable.
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_USas locale, the following replacements occur:If the locale is
de_DE, this would be the result:Because
äis part of[[:alpha:]]in this particular locale. The obvious solution to circumvent this would be to substitute the character class for[a-zA-Z].