如何在 PHP 中用正则表达式替换所有实际上不是空格的空格

How to replace all spaces which are not actually spaces with regex in PHP

我有以下字符串,我想从多个空格中 'clean':

$string = "This is   a test string"; //Using utf8_decode

没什么大不了的吧?但是,使用后字符串不是'cleaned':

$string = preg_replace('/\s+/', ' ', $string);

因为,字符串实际上是这样的:

$test = "This is a  test string";

那么,我该如何解决这个问题?

谢谢。

拜托,我不想替换 str_replace('Â', '') 之类的字符

您可以使用 /u UNICODE 修饰符:

$string = preg_replace('/\s+/u', ' ', $string);

The /u modifier enables the PCRE engine to handle strings as UTF8 strings (by turning on PCRE_UTF8 verb) and make the shorthand character classes in the pattern Unicode aware (by enabling PCRE_UCP verb)

要点是 \s 现在将匹配所有 Unicode 空格并且输入字符串被视为 Unicode 字符串。