Help us understand the problem. What is going on with this article?

substr() で length指定するとき、元の文字列長チェックは不要

More than 1 year has passed since last update.

こんなコードを見かけた。

define('STR_LENGTH_MAX', 255);
$str = getSomeLongString(); //何か長いかもしれない文字列を返す関数
if (strlen($str) > STR_LENGTH_MAX){
    $str = substr($str, 0, STR_LENGTH_MAX);
}

実装した人はおそらく素朴に「規定の文字列長以上だったら切り詰める」を実装したのだろう。

もちろんこれでも動くが、そもそもこんなことしなくても

substr() の第3引数で指定した文字列長より、第1引数で渡した文字列が短い場合

substr() は元の文字列をそのまま帰すので、この実装は単純に

define('STR_LENGTH_MAX', 255);
$str = substr(getSomeLongString(), 0, STR_LENGTH_MAX);

でOK。

念のため、実証コードを掲載。

$ cat test.php
<?php
error_reporting(E_ALL);

$str = 'abcdefghijklmn';
for ($i = 1;$i<20;$i++){
    echo substr($str,0,$i), PHP_EOL;
}

$ php test.php 
a
ab
abc
abcd
abcde
abcdef
abcdefg
abcdefgh
abcdefghi
abcdefghij
abcdefghijk
abcdefghijkl
abcdefghijklm
abcdefghijklmn
abcdefghijklmn
abcdefghijklmn
abcdefghijklmn
abcdefghijklmn
abcdefghijklmn

$str の文字列の長さより、substr() の第3引数のほうが大きい場合
$str そのものが返却されていることがわかる。
エラーも特におきない。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away