Check if a String Contains a Specific Word PHP

If you would like to check if a string contains a specific word in PHP, you have a couple options, but, we tend to prefer PHP’s strpos function.

If the needle is not found in the haystack, strpos returns false.

If the needle is found in the haystack, strpos returns the position of the needle relative to the start of the string, starting at 0.

$string = 'bozo';
$find   = 'b';
// position equals 0
$position = strpos($string, $find);

// Make sure to use === instead of ==, as it won't work as expected because the position of the letter b was the first character.
if ($position === false) {
    // the character doesn't exist in the string
}

if ($position !== false) {
    // the character exists at in the string 
}

Leave a Reply

Your email address will not be published. Required fields are marked *