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

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

strpos()

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

$str = 'I like apples.';

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

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

strstr()

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

$str = 'I like apples.';

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

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

preg_match()

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

$str = 'I like apples.';

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

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

まとめ

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

参考