I need to remove all characters in a string except dashes, letters, numbers, spaces, and underscores.
Various answers on SO come tantalizingly close (Replace all characters except letters, numbers, spaces and underscores, Remove all characters except letters, spaces and apostrophes, etc.) but generally don't include dashes.
Help would be greatly appreciated.
You could do something like below:
$string = ';")<br>kk23how nowbrowncow_-asdjhajsdhasdk32423ASDASD*%$@#!^ASDASDSA4sadfasd_-?!';
$new_string = preg_replace('/[^ \w-]/', '', $string);
echo $new_string;
[^]
represents a list of characters NOT to match\w
is a short for word character [A-Za-z0-9_]
-
matches a hyphen literallyYou probably need something like:
$new = preg_replace('/[^ \w-]/', '', $old);
Explanation:
[^ \w-]
Match any single character NOT present in the list below «[^ \w-]»
The literal character “ ” « »
A “word character” (Unicode; any letter or ideograph, any number, underscore) «\w»
The literal character “-” «-»