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

DDD
Release: 2024-11-14 10:11:01
Original
335 people have browsed it

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

Determining String Inclusion from an Array (Case-Insensitive)

In programming, you may encounter situations where you need to verify if a given string contains any matches from an array of items. Specifically, you want to check for case-insensitive matches.

The Requirement:

Suppose you have a string variable ($string) and an array ($array) containing specific keywords. You want to create a function called "contains()" to determine if $string contains any of the keywords in $array, regardless of case.

The Solution:

Native programming languages often do not provide a built-in function to handle this scenario. Therefore, we recommend implementing a custom "contains()" function:

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 takes a string ($str) and an array $arr as input. It iterates through each item in $arr using a foreach loop. For each item $a, it uses the stripos() function to check if it exists within $str, ignoring case differences. If any of the array items are present in $str, the function returns true. Otherwise, it returns false.

The above is the detailed content of How to Check if a String Contains Any Keyword 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