3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PCRE関数(preg系関数)で Unicode なコードを16進で指定

Posted at

PCRE関数(preg系関数)で \x{hhh...} の形式で Unicode なコードを16進で指定できます。

<?php
preg_match('/[\\x{3044}-\\x{3048}]+/u', 'あいうえお', $m);
var_dump($m[0]); // いうえ

サロゲートペアのような、エディタでの表示が困難な文字を指定するときに便利です。

<?php
// UTF-16 のサロゲートペアな文字
$u32 = hex2bin('000201A2');

$u08 = mb_convert_encoding($u32, 'UTF-8', 'UCS-4BE');
var_dump($u08); // でかい ^ みたいな文字
var_dump(bin2hex($u08)); // f0a086a2

$u16 = mb_convert_encoding($u32, 'UTF-16', 'UCS-4BE');
var_dump(bin2hex($u16)); // d840dda2

// 正規表現を `\x{hhh...}` の形式で指定
$r = preg_match('/\\x{201A2}/u', $u08, $m);
var_dump($r, $m[0]);

// 文字列リテラルのエスケープシーケンスで UTF-8 のコードを指定
$r = preg_match("/\xF0\xA0\x86\xA2/u", $u08, $m);
var_dump($r, $m[0]);

UTF-8 なバイトシーケンスを "/\xF0\xA0\x86\xA2/u" などと指定するより楽です。

参考

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?