如何使用正则表达式在PHP中正确删除UTF8字符串中的重复空白字符?

ana*_*ndr 5 php regex whitespace utf-8

我正在尝试使用正则表达式从PHP中的UTF8字符串中删除重复的空白字符.这个正则表达式

    $txt = preg_replace( '/\s+/i' , ' ', $txt );
Run Code Online (Sandbox Code Playgroud)

通常工作正常,但有些字符串有西里尔字母"Р",更换后拧紧.经过小规模的研究后,我意识到这个字母被编码为\ x {D0A0},并且因为\ xA0是ASCII中的非破坏空格,所以正则表达式用\ x20替换它并且该字符不再有效.

有关如何在PHP中使用正则表达式正确执行此操作的任何想法?

Pas*_*rby 5

尝试u修饰符:

$txt="UTF ??? with ????";
var_dump(preg_replace("/\\s+/iu","",$txt));
Run Code Online (Sandbox Code Playgroud)

输出:

string(28) "UTF???with????"
Run Code Online (Sandbox Code Playgroud)


asc*_*moo 4

它被描述@http ://www.php.net/manual/en/function.preg-replace.php#106981

如果你想捕捉字符,以及欧洲、俄罗斯、中国、日本、韩国等,只需:

  • 使用 mb_internal_encoding('UTF-8');
  • 将 preg_replace(' ...u', '...', $string) 与 u (unicode) 修饰符一起使用

有关更多信息,可以在以下位置找到 preg_* 修饰符的完整列表: http://php.net/manual/en/reference.pcre.pattern.modifiers.php