PHP preg 替换白帽字符

PHP preg replace whitehat characters

此正则表达式保留字母和数字并删除其余部分

它按预期工作:

$content = preg_replace('~\P{Xan}+~u', '', $string);

我尝试对某些字符进行白帽处理,但它不起作用

我在下面尝试白帽点、逗号、减号和space:

$content = preg_replace('~\P{Xan}.,- +~u', '', $string);

相反,它允许一切,甚至是奇怪的字符。

我怎样才能让它像以前一样工作,但只是白帽子一些特殊字符?

很遗憾,PHP 中的 PCRE 不支持 character class intersection, nor subtraction

您可以使用否定字符 class 和反向 shorthand Unicode 类别 class:

'~[^\p{Xan}., +-]+~u'

\P{Xan} = [^\p{Xan}],但我们可以在否定字符class中添加更多字符,其含义将*匹配除\p{Xan}以外的字符,.,、space、+-

另一种方法是使用前瞻性限制通用子模式(但不要忘记将该子模式放入组中,因为量词应应用于生成的 (?:(?![., +-])\P{Xan}) 构造):

'~(?:(?![., +-])\P{Xan})+~u'