我该如何使用PHP去除所有不是字母、数字、空格或标点符号的字符?
我尝试了以下代码,但它会去除标点符号。
preg_replace("/[^a-zA-Z0-9\s]/", "", $str);
我该如何使用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 字符属性)。如果您只想允许特定的标点符号,请将它们添加到否定字符类中。例如:
preg_replace("/[^a-zA-Z0-9\s.?!]/", "", $str);
由于没有缩写符号表示标点符号(例如,\s
代表空格字符),您需要明确列出标点符号。
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);
让我们为这个任务构建一个多字节安全/Unicode安全的模式。
来自https://www.regular-expressions.info/unicode.html:
\p{L} 或 \p{Letter}:来自任何语言的任何字母。
\p{Z} 或 \p{Separator}:任何种类的空格或不可见分隔符。
\p{N} 或 \p{Number}:任何脚本中的任何数字字符。
\p{P} 或 \p{Punctuation}:任何种类的标点符号字符。
[^ ... ]
是一个否定字符类,匹配不在列表中的任何字符。+
是一个“一个或多个”的量词。u
此修饰符打开了 PCRE 的其他功能,与 Perl 不兼容。模式和主题字符串被视为 UTF-8。无效的主题将导致 preg_* 函数匹配到空;无效的模式将触发 E_WARNING 级别的错误。五个和六个八位 UTF-8 序列被视为无效。代码:(演示)
echo preg_replace('/[^\p{L}\p{Z}\p{N}\p{P}]+/u', '', $string);
--enable-unicode-properties
编译。 - Matthew Flaschen