非破坏性的utf-8 0xc2a0空间和preg_replace奇怪的行为

Dam*_*irR 32 php regex

在我的字符串中,我有utf-8非破坏空间(0xc2a0),我想用其他东西替换它.

我用的时候

$str=preg_replace('~\xc2\xa0~', 'X', $str);
Run Code Online (Sandbox Code Playgroud)

它运作正常.

但是当我使用时

$str=preg_replace('~\x{C2A0}~siu', 'W', $str);
Run Code Online (Sandbox Code Playgroud)

找不到(并替换)不间断的空间.

为什么?第二个正则表达式有什么问题?

格式\x{C2A0}是正确的,我也用u旗帜.

New*_*o.O 54

实际上PHP中关于转义序列的文档是错误的.使用\xc2\xa0语法时,它会搜索UTF-8字符.但是使用\x{c2a0}语法,它会尝试将Unicode序列转换为UTF-8编码字符.

非中断空间是U+00A0(Unicode),但编码为C2A0UTF-8.因此,如果您尝试使用该模式~\x{00a0}~siu,它将按预期工作.

  • [本文](http://rrn.dk/the-difference-between-utf-8-and-unicode)非常了解这个主题.还有[这个问题](http://stackoverflow.com/questions/3951722/whats-the-difference-between-unicode-and-utf8),其中前一篇文章已被复制/粘贴. (3认同)

hug*_*ugs 12

我已经开始研究以前的答案,以便人们可以复制/粘贴以下代码来选择他们喜欢的方法:

$some_text_with_non_breaking_spaces = "some text with 2 non breaking spaces at the beginning";
echo 'Qty non-breaking space : ' . substr_count($some_text_with_non_breaking_spaces, "\xc2\xa0") . '<br>';
echo $some_text_with_non_breaking_spaces . '<br>';

# Method 1 : regular expression
$clean_text = preg_replace('~\x{00a0}~siu', ' ', $some_text_with_non_breaking_spaces);

# Method 2 : convert to bin -> replace -> convert to hex
$clean_text = hex2bin(str_replace('c2a0', '20', bin2hex($some_text_with_non_breaking_spaces)));

# Method 3 : my favorite
$clean_text = str_replace("\xc2\xa0", " ", $some_text_with_non_breaking_spaces);

echo 'Qty non-breaking space : ' . substr_count($clean_text, "\xc2\xa0"). '<br>';
echo $clean_text . '<br>';
Run Code Online (Sandbox Code Playgroud)