简体   繁体   English

preg_replace删除除破折号,字母,数字,空格和下划线以外的所有字符

[英]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;

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

Demo 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM