[英]preg_replace to remove all characters except dashes, letters, numbers, spaces, and underscores
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. SO上的各种答案都非常接近( 替换字母,数字,空格和下划线 以外的所有字符 , 删除字母,空格和撇号等以外的所有字符 ),但通常不包括破折号。
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_]
\\w
是单词字符 [A-Za-z0-9_]
的缩写 -
matches a hyphen literally -
从字面上匹配连字符 You 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 “-” «-»
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.