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 }
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; }
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!