5

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

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

通常工作正常,但有些琴弦有西里尔字母“Р”,更换后拧紧。经过小型研究,我意识到该字母被编码为 \x{D0A0},并且由于 \xA0 是 ASCII 中的不间断空格,因此正则表达式将其替换为 \x20 并且该字符不再有效。

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

4

2 回答 2

5

试试u修饰符:

$txt="UTF 字符串 with 空格符號";
var_dump(preg_replace("/\\s+/iu","",$txt));

输出:

string(28) "UTF字符串with空格符號"
于 2012-11-19T08:36:55.793 回答
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

于 2012-11-19T08:37:21.297 回答