LoginSignup
1
1

More than 3 years have passed since last update.

絵文字をカウントするにはマルチバイト対応の正規表現でも対応できない

Last updated at Posted at 2019-06-13

👨‍👨‍👦‍👦のような合成絵文字が入ると無理っぽい。
こちらを見ていたら正規表現的な考え方もできるのかなと思い試したところ無理でした。

コメントにあるように
each_graphemeのように実装して判定するそうです。

私が試してみたもの(合成絵文字に対応できてない)

$string = 'aaaああああ
👿👿👿
👿👿👿
👿👿👿👿👿

👿👿👿


';


$width = 3;
do {
$string = preg_replace('/([^\n]{' . $width. '})([^\n])/u', "$1\n$2", $string, 1, $count);
} while ($count > 0);

var_dump($string);
string(82) "aaa
あああ
あ
👿👿👿
👿👿👿
👿👿👿
👿👿

👿👿👿


"

あれ?違う端末でみたら一文字じゃなくて複数文字に見えるからどっちに合わせるかの問題もありそう…

絵文字を削除したりするのは可能

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