【问题标题】:Does preg_replace() change my character set?preg_replace() 会改变我的字符集吗?
【发布时间】:2013-11-06 22:27:42
【问题描述】:

我有以下似乎正在改变我的字符集的代码。

     $html = "à";
     echo $html;  // result: à
     $html = preg_replace("/\s/", "", $html);
     echo $html;  // result: ?

但是,当我使用 [\t\n\r\f\v] 而不是特殊字符 \s 作为我的模式时,它可以正常工作:

     $html = "à";
     echo $html;  // result: à
     $html = preg_replace("/[\t\n\r\f\v]/", "", $html);
     echo $html;  // result: à

这是为什么呢?

【问题讨论】:

  • 两者都为我提供相同的输出。 ideone.com/Xo7RLR
  • 你用的是什么版本的PHP?
  • @user4035 PHP 版本 5.3.24

标签: php regex encoding character-encoding special-characters


【解决方案1】:

我也有同样的问题。这是因为UTF8。

à 在 UTF8 中是 0xc3a0。在 PHP 中你可以这样写:"\xc3\xa0".

使用 PCRE,/s 匹配 0xa0,就像 ASCII“不间断空格”一样。

您可以使用u flag 解决问题。

$html = preg_replace("/\s/u", "", $html);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多