9
7

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.

PHP:UTF-8の文字を1文字ずつに区切る方法

Last updated at Posted at 2018-12-07

PHPではpreg_splitで、UTF-8の文字を1文字ずつに区切ることができる。

preg_split('//u', $区切りたい文字列, -1, PREG_SPLIT_NO_EMPTY);
  • 第一引数: '//u'
    • //: 1文字ごとに区切る。
    • u (PCRE_UTF8): パターンと対象文字列は、UTF-8として処理される。UTF-8の1文字(1コードポイント)ごとに区切られるようになる。
  • 第三引数: -1
    • 分割数の上限を儲けない設定。
  • 第四引数: PREG_SPLIT_NO_EMPTY
    • 空文字列じゃないものだけが、戻り値の配列の要素になる。
    • 例えば、$区切りたい文字列 = '';のとき、['', '']が返ってくるのを抑制する働きがある。

デモ

var_dump(preg_split('//u', 'A1Ä①⌘あ漢😊🐬🙌🏻👨🏻‍💻', -1, PREG_SPLIT_NO_EMPTY));
array(15) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "1"
  [2]=>
  string(2) "Ä"
  [3]=>
  string(3) "①"
  [4]=>
  string(3) "⌘"
  [5]=>
  string(3) "あ"
  [6]=>
  string(3) "漢"
  [7]=>
  string(4) "😊"
  [8]=>
  string(4) "🐬"
  [9]=>
  string(4) "🙌"
  [10]=>
  string(4) "🏻"
  [11]=>
  string(4) "👨"
  [12]=>
  string(4) "🏻"
  [13]=>
  string(3) "‍"
  [14]=>
  string(4) "💻"
}

UTF-8の1コードポイントごとに分解されるので、ひらがなや漢字はおおかた期待通りだが、合成絵文字とか異体字セレクタまで考慮しての分解は流石に無理っぽい。このへんのUTF-8の深淵は、『絵文字を支える技術の紹介』『人名や地名に含まれる異体字を壊さないようにするために grapheme_substr もしくは grapheme_extract を使う』を読むといい。

9
7
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
9
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?