如何检查字符串是否包含数组中的任何关键字(不区分大小写)?

DDD
发布: 2024-11-14 10:11:01
原创
336 人浏览过

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;
}
登录后复制

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.

以上是如何检查字符串是否包含数组中的任何关键字(不区分大小写)?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板