Efficiently Checking for Element Presence in a String
Determining whether a string contains any item from an array is a common programming scenario. While standard programming languages may lack built-in functions for this specific task, it is relatively straightforward to create a custom function to achieve this functionality.
Consider the example:
$string = 'My nAmE is Tom.'; $array = array("name","tom");
To check if the string contains any of the items in the array, a contains() function can be defined:
function contains($str, array $arr) { foreach($arr as $a) { if (stripos($str,$a) !== false) return true; } return false; }
This function iterates through the array's elements, performing a case-insensitive search for each element within the string using stripos(). If any matching element is found in the string, the function returns true, indicating its presence. Otherwise, it returns false.
By using this custom function, we can efficiently check whether the provided string contains any of the items in the array, as demonstrated in the following usage:
if(contains($string,$array)) { // do something to indicate the presence of an item }
The above is the detailed content of How to Efficiently Check for Element Presence in a String?. For more information, please follow other related articles on the PHP Chinese website!