0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PHPで日本語の文字数を正しくカウントする方法

Last updated at Posted at 2024-09-14

概要

  • バリデーションのテストをおこなったところ、日本語に対する正しい判定を行えていないことが分かった
  • 正しい判定方法を備忘録として残しておく

理由

if (strlen($name) > 50) {

もともとこのようにバリデーションを行っていたが、「あ」を50回繰り返したところエラーが発生してしまった

function strlen(string $string): int
文字列の長さを得る

与えられた string の長さを返します。

https://www.php.net/manual/function.strlen.php

@param $string: 長さを調べる文字列。

@return string の長さをバイト単位で返します。

原因は単純で、バイト単位でカウントするため2倍カウントされてしまっていることが原因であった

解決方法

function mb_strlen(
string $string,
string|null $encoding = null
): int
文字列の長さを取得します。

https://www.php.net/manual/function.mb-strlen.php

@param $string: 長さを調べたい文字列。

@param $encoding: encoding パラメータには文字エンコーディングを指定します。省略した場合、もしくは null の場合は、 内部文字エンコーディングを使用します。

@return 文字エンコーディング encoding の文字列 string の文字数を返します。 マルチバイト文字の一文字は1個として数えられます。

これまでの部分をこのように置き換えることで、意図したように日本語の文字数をカウントすることが可能となる

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?