strpos with Arrays: A Deeper Dive
In PHP, the strpos function searches for a string within another string. Often, we encounter situations where we want to search for multiple strings simultaneously. While the provided code fails to perform this task, we can explore alternative solutions using an array of search terms.
Custom Function for Array Needles
One approach is to create a custom function that mimics the functionality of strpos for an array of needles:
function strposa($haystack, $needles=array(), $offset=0) { $chr = array(); foreach($needles as $needle) { $res = strpos($haystack, $needle, $offset); if ($res !== false) $chr[$needle] = $res; } if(empty($chr)) return false; return min($chr); }
This function takes a haystack string, an array of needles to search for, and an optional offset. It returns the index of the first occurrence of any of the needles, or false if none are found.
Improved Custom Function
To enhance this function, we can stop the search once the first needle is found:
function strposa(string $haystack, array $needles, int $offset = 0): bool { foreach($needles as $needle) { if(strpos($haystack, $needle, $offset) !== false) { return true; } } return false; }
This updated function scans the haystack for each needle in the array and returns true as soon as it finds a match. It's more efficient when multiple needles may be present in the haystack.
Usage Examples
To use these functions, simply pass the haystack string and the array of needles as arguments.
$string = 'This string contains word "cheese" and "tea".'; $array = ['burger', 'melon', 'cheese', 'milk']; if(strposa($string, $array)) { echo 'true'; // since "cheese" is found }
In this example, the script outputs true because "cheese" is a substring of the haystack.
The above is the detailed content of How Can I Efficiently Search for Multiple Substrings within a String in PHP Using Arrays?. For more information, please follow other related articles on the PHP Chinese website!