Php 正则表达式:去除非字母数字或标点符号

Php 正则表达式:去除非字母数字或标点符号,php,regex,string,Php,Regex,String,如何使用PHP去除所有不是字母、数字、空格或puncutation的字符 我试过下面的方法,但它去掉了标点符号 preg_replace("/[^a-zA-Z0-9\s]/", "", $str); 您必须明确列出标点符号,因为标点符号没有速记(例如\s是空白字符的速记) preg\u replace('/[^a-zA-Z0-9\s\-=+\\\\\!@$%^&*()`~\[\]{};:\',\/?]/','$str); 例如: php > echo preg_replace("/[^

如何使用PHP去除所有不是字母、数字、空格或puncutation的字符

我试过下面的方法,但它去掉了标点符号

preg_replace("/[^a-zA-Z0-9\s]/", "", $str);

您必须明确列出标点符号,因为标点符号没有速记(例如
\s
是空白字符的速记)

preg\u replace('/[^a-zA-Z0-9\s\-=+\\\\\!@$%^&*()`~\[\]{};:\',\/?]/','$str);
例如:

php > echo preg_replace("/[^a-zA-Z0-9\s\p{P}]/", "", "⟺f✆oo☃. ba⟗r!");
foo. bar!
\p{p}
匹配所有Unicode标点字符(请参见Unicode)。如果您只想允许特定标点,只需将它们添加到否定字符类中即可。例如:

preg_replace("/[^a-zA-Z0-9\s.?!]/", "", $str);

希望这会有所帮助。

第二个会。第一个允许所有标点符号。这些符号似乎会去除所有字符:(我使用的是你的第一个示例,这似乎会去除所有字符。我做错了什么?@Tedd,不确定。我发布了一个测试示例。其中提到了一些注意事项。你必须在4.4或5.1之后使用PHP(取决于分支),以及UTF-8,并且必须使用
--启用unicode属性编译PCRE库
php > echo preg_replace("/[^a-zA-Z0-9\s\p{P}]/", "", "⟺f✆oo☃. ba⟗r!");
foo. bar!
preg_replace("/[^a-zA-Z0-9\s.?!]/", "", $str);
$str = trim($str);
$str = trim($str, "\x00..\x1F");
$str = str_replace(array( ""","'","&","<",">"),' ',$str);
$str = preg_replace('/[^0-9a-zA-Z-]/', ' ', $str);
$str = preg_replace('/\s\s+/', ' ', $str); 
$str = trim($str);
$str = preg_replace('/[ ]/', '-', $str);