How to Check if a String Contains Any Element from an Array (Case-Insensitive)?

DDD
Release: 2024-11-12 10:49:02
Original
319 people have browsed it

How to Check if a String Contains Any Element from an Array (Case-Insensitive)?

Checking for String Containment Within an Array (Case-Insensitive)

Question:

How can a string be checked to determine if it includes any of the elements within an array, regardless of case differences?

Code Example:

$string = 'My nAmE is Tom.';
$array = array("name", "tom");
if (contains($string, $array)) {
    // Perform an action indicating that the string contains an element from the array
}
Copy after login

Solution:

There is no built-in function designed specifically for this purpose. However, a custom contains() function can be created as follows:

function contains($str, array $arr)
{
    foreach ($arr as $a) {
        if (stripos($str, $a) !== false) {
            return true;
        }
    }
    return false;
}
Copy after login

Explanation:

The contains() function iterates through each element in the $arr array. For each element, it uses stripos() to check if it exists within the $str string, considering case insensitivity. If any element is found within the string, the function returns true. Otherwise, it returns false, indicating that none of the array elements were found in the string.

The above is the detailed content of How to Check if a String Contains Any Element from an Array (Case-Insensitive)?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template