34

私の文字列には utf-8 改行なしスペース (0xc2a0) があり、それを別のものに置き換えたいと考えています。

私が使うとき

$str=preg_replace('~\xc2\xa0~', 'X', $str);

それは正常に動作します。

しかし、私が使用するとき

$str=preg_replace('~\x{C2A0}~siu', 'W', $str);

非改行スペースは見つかりません (そして置き換えられます)。

なんで?2番目の正規表現の何が問題になっていますか?

フォーマット\x{C2A0}は正しいです。また、uフラグを使用しました。

4

5 に答える 5

60

実際、PHP のエスケープ シーケンスに関するドキュメントは間違っています。構文を使用\xc2\xa0すると、UTF-8 文字が検索されます。ただし、\x{c2a0}構文では、Unicode シーケンスを UTF-8 エンコード文字に変換しようとします。

非改行スペースはU+00A0(Unicode) ですがC2A0、UTF-8 としてエンコードされます。したがって、パターンを試してみると、~\x{00a0}~siu期待どおりに機能します。

于 2012-10-11T11:10:45.167 に答える
13

以前の回答をまとめたので、次のコードをコピー/貼り付けして、お気に入りの方法を選択できます。

$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>';
于 2015-05-07T12:42:46.940 に答える
3

私の意見では、2 つのコードは異なることを行います。最初のコードは 2文字を\xc2\xa0置き換え、何も置き換えません。\xc2\xa0

UTF-8 エンコーディングでは、これはU+00A0.

機能します\x{00A0}か?これは の表現である必要があります\xc2\xa0

于 2012-10-11T11:12:00.970 に答える
1

このバリアントは動作しませんでした~\x{c2a0}~siu

バリアン\x{00A0}作品。2 番目のオプションは試していませんが、結果は次のとおりです。

0xC2 0xA0 (c2a0)私はそれを hex に変換し、 no-break spaceを space に置き換えようとしました0x20 (20)

コード:

$hex = bin2hex($item);
$_item = str_replace('c2a0', '20', $hex);
$item = hex2bin($_item);
于 2014-07-24T08:56:19.090 に答える