【PHP】特定の文字列を含むか確認する方法3選

strpos()

文字列内の部分文字列が最初に現れる場所を見つける関数。
文字列が見つかればint型で位置が、無ければfalseが返されます。


$str = 'I like apples.';

if (false !== strpos($str, 'apple')) {
    // $strにappleが含まれる場合
}

if (false === strpos($str, 'apple')) {
    // $strにappleを含まない場合
}

strstr()

文字列が最初に現れる位置を見つける関数。
文字列が見つかればその文字列を含む末尾までも文字列が、無ければfalseが返されます。


$str = 'I like apples.';

if (false !== strstr($str, 'apple')) {
    // $strにappleが含まれる場合
}

if (false === strstr($str, 'apple')) {
    // $strにappleを含まない場合
}

preg_match()

正規表現によるマッチングを行う関数。
文字列が見つかればint型で1が、無ければ0が返されます。


if (1 === preg_match('/apple/', $str)) {
    // $strにappleが含まれる場合
}

if (0 === preg_match('/apple/', $str)) {
    // $strにappleを含まない場合
}

まとめ

strpos()strstr()preg_match()よりもメモリ消費量が少なく高速なため、
単純に文字列が含まれているかどうかを判別するだけなら、strpos()を使うのが良さそうです。

参考