LoginSignup
0
1

More than 3 years have passed since last update.

PHP strpos()関数の注意点

Posted at

文字列の中に特定の文字列があるかどうかの判定を行うためにstrpos()を使用するが、注意が必要である。

strpos()

if(strpos($対象となる文字列, $特定の文字列)){
    //省略
}

返り値

特定する文字列があった場合

 →最初の文字のインデックス番号
  例:helloの特定文字列、ellの返り値は1

特定する文字列がない場合

 →(bool)false

注意(これが今回のメイン)

strpos('hello', 'ell')
の返り値は1。
しかし
strpos('hello', 'hell')
の返り値は0になる。(当然だけど)

だからif文を使用する場合、'hell'という特定の文字列があったとしても、
結果はfalseになる。(返り値が0だから)

解決策

返り値はint型もしくはfalse(bool型)だから、この両方をtrueの結果にしてあげる必要がある。

$i = 'hello';
if(strpos($i, 'hell') !== false){
    echo 'including';
}else{
    echo 'not including';
}

//結果 including
$i = 'hello';
if(strpos($i, 'ell') !== false){
    echo 'including';
}else{
    echo 'not including';
}

//結果 including
$i = 'hello';
if(strpos($i, 'abc') !== false){
    echo 'including';
}else{
    echo 'not including';
}

//結果 not including
$i = 'hello123';
if(strpos($i, 'o1') !== false){
    echo 'including';
}else{
    echo 'not including';

//結果 including
0
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
0
1