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中文网其他相关文章!