Check if String Contains Any of Array in PHP

This tutorial will discuss how to check if string contains any of array in PHP.

Suppose we have a string and an array of strings.

// A string
$strValue = 'This is some Random Text.';

// An Array of strings
$words = ['Document', 'some', 'Today', 'Final'];

Now, we want to check if the string contains any word from the array. For this, we can iterate over each word in the array, and for each word, we can use the strpos() function to check if it exists in the original string. If strpos() returns a non-negative value, it means the word is found in the string.

We have created a separate function for this purpose,

function contains($strValue, $array)
{
    foreach ($array as $value) {
        if (strpos($strValue, $value) !== false) {
            return true;
        }
    }
    return false;
}

It accepts a string as an argument and returns true if the string contains any element from the array. The function iterates over each word in the array and uses strpos() to perform the check.

Let’s see the complete example,

<?php
/**
 * Check if a string contains any string from an array.
 *
 * @param string $strValue The string to validate.
 * @param array $array The array of strings to search for.
 * @return bool True if the string contains any string from
 *              the array, false otherwise.
 */
function contains($strValue, $array)
{
    foreach ($array as $value) {
        if (strpos($strValue, $value) !== false) {
            return true;
        }
    }
    return false;
}

// A string
$strValue = 'This is some Random Text.';

// An Array of strings
$words = ['Document', 'some', 'Today', 'Final'];

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

Output

The string contains a word from the array.

Summary

Today, we learned how to check if string contains any of array 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