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.

PHPマルチバイト文字列の切り取り(メモ)

Last updated at Posted at 2016-02-03

PHPでマルチバイト文字列の切り取りに迷ったのでメモ。

substr … 文字列を任意の箇所から任意バイト数切り取り

 第1引数:対象の文字列
 第2引数:切り取り開始位置(バイト)
 第3引数:切り取り開始のバイト数

var_dump(substr("mojiretsu", 0, 2)); // string(2) "mo"
var_dump(substr("ごりら", 0, 3)); // string(3) "ご"

mb_substr … 文字列を任意の箇所から任意文字数切り取り

 第1引数:対象の文字列
 第2引数:切り取り開始位置
 第3引数:切り取り開始の文字数
 第4引数:文字エンコーディング

var_dump(mb_substr("mojiretsu", 0, 2, "UTF-8")); // string(2) "mo"
var_dump(mb_substr("ごりら", 0, 3, "UTF-8")); // string(9) "ごりら"
3
2
1

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?