preg_replace删除除短划线,字母,数字,空格和下划线之外的所有字符

时间:2017-04-14 03:57:17

标签: php regex

除了破折号,字母,数字,空格和下划线之外,我需要删除字符串中的所有字符。

关于SO的各种答案非常接近(Replace all characters except letters, numbers, spaces and underscoresRemove all characters except letters, spaces and apostrophes等),但通常不包括破折号。

非常感谢帮助。

2 个答案:

答案 0 :(得分:4)

您可以执行以下操作:

    $string = ';")<br>kk23how nowbrowncow_-asdjhajsdhasdk32423ASDASD*%$@#!^ASDASDSA4sadfasd_-?!'; 
    $new_string = preg_replace('/[^ \w-]/', '', $string);
    echo $new_string;

答案 1 :(得分:2)

您可能需要以下内容:

$new = preg_replace('/[^ \w-]/', '', $old);

<强>解释

[^ \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 “-” «-»

Demo