如何使用 PHP 去除所有非字母、数字、空格或标点符号的字符?
我尝试了以下方法,但它会删除标点符号。
preg_replace("/[^a-zA-Z0-9\s]/", "", $str);
最佳答案
preg_replace("/[^a-zA-Z0-9\s\p{P}]/", "", $str);
例子:
php > echo preg_replace("/[^a-zA-Z0-9\s\p{P}]/", "", "⟺f✆oo☃. ba⟗r!");
foo. bar!
\p{P}
匹配所有 Unicode 标点字符(参见 Unicode character properties)。如果您只想允许特定的标点符号,只需将它们添加到否定字符类。例如:
preg_replace("/[^a-zA-Z0-9\s.?!]/", "", $str);
关于php - 正则表达式:去除非字母数字或标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3050352/