我在浏览Stack Overflow的答案时发现,大多数人提供的替换多个空格的解决方案是:
$new_str = preg_replace("/\s+/", " ", $str);
但是在许多情况下,空格字符包括包含换行、形式进纸、回车、不间断空格等的UTF字符。 这个维基 描述了UTF定义的25个空白字符。
那么我们如何使用正则表达式替换所有这些字符呢?
当使用 u
修饰符时,\s
将会变得 Unicode - 感知。因此,一个简单的解决方案是使用
$new_str = preg_replace("/\s+/u", " ", $str);
^^
查看 PHP 在线演示。
$str = "Hello there".str_repeat(json_decode('"\u00A0"'),10)."Bob!";
该字符串有10个由utf代码00A0
表示的不间断空格。您可以先尝试echo该字符串以查看其效果。 - Adam Ranganathan$utf = "Hello there".str_repeat(json_decode('"\u00A0"'),10)."Bob!"; $new_str = preg_replace("/\s+/u", " ", $utf); echo $new_str;
- Adam Ranganathan匹配所有Unicode空白字符的模式是[\pZ\pC]
。这里有一个单元测试证明它。
如果你正在解析UTF-8编码的用户输入,并且需要对其进行规范化,那么基于该列表进行匹配非常重要。因此,回答你的问题是:
$new_str = preg_replace("/[\pZ\pC]+/u", " ", $str);
$pattern = "/<our-pattern-here>/u";
\x{00A0}
,其中00A0
是不间断空格
的十六进制表示。因此,如果我们想用单个空格替换连续的不间断空格,我们可以这样做:$pattern = "/\x{00A0}+/u";
$new_str = preg_replace($pattern," ",$str);
如果我们要包括维基中提到的其他类型的空格,比如:
\x{000D}
回车符\x{000C}
换页符\x{0085}
下一行我们的模式变为:
$pattern = "/[\x{00A0}\x{000D}\x{000C}\x{0085}]+/u";
|
分隔字符:$pattern = "/\x{00A0}|\x{000D}|\x{000C}|\x{0085}/u";
$new_str = preg_replace($pattern," ",$str); // we have one-to-one replacement of character by a normal space, so 5 unicode chars give 5 normal spaces
$final_str = preg_replace("/\s+/", " ", $new_str); // multiple normal spaces now become single normal space