Check if String Contains a Word in PHP

This tutorial will discuss how to check if string contains a word in PHP.

To check if a string contains a specific word in PHP, we can use the strpos() function.

We convert both the string and the word to lowercase using the strtolower() function before calling strpos(). This allows us to perform a case-insensitive search.

If strpos() finds the occurrence of the word in the string, it will return the index position where the word starts. In that case, we can consider it as a successful match. If the word is not found, strpos() will return false.

We have created a separate function,

function contains($strValue, $word)
{
    // Convert the string and word to lowercase for
    // case-insensitive comparison
    $lowercaseString = strtolower($strValue);
    $lowercaseWord = strtolower($word);

    // Use strpos() to check if the word exists in the string
    return strpos($lowercaseString, $lowercaseWord) !== false;
}

It accepts a string and a word as arguments. The function converts both the string and the word to lowercase and uses strpos() to check if the string contains the word in a case-insensitive manner. If a match is found, the function returns true.

Let’s see the complete example,

<?php
/**
 * Check if a string contains a specific word in
 * case insensitive manner.
 *
 * @param string $strValue The string to validate.
 * @param string $word The word to search for.
 * @return bool True if the string contains the word,
 *              False otherwise.
 */
function contains($strValue, $word)
{
    // Convert the string and word to lowercase for
    // case-insensitive comparison
    $lowercaseString = strtolower($strValue);
    $lowercaseWord = strtolower($word);

    // Use strpos() to check if the word exists in the string
    return strpos($lowercaseString, $lowercaseWord) !== false;
}


$strValue = 'This is a sample string.';
$word = 'sample';

// Check if string contains a word
if (contains($strValue, $word)) {
    echo "The string contains the word '$word'.";
} else {
    echo "The string does not contain the word '$word'.";
}
?>

Output

The string contains the word 'sample'.

Summary

Today, we learned how to check if string contains a word in PHP.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top