Home >Backend Development >PHP Tutorial >How Can I Efficiently Search a String for Multiple Substrings Using PHP?
Using an Array for Searching Strings with strpos
The strpos function is commonly used to locate the position of a substring within a string. However, it can sometimes be useful to search for multiple substrings simultaneously using an array of needles.
The Problem
Unfortunately, the standard implementation of strpos does not allow us to pass an array of needles. Attempting to do so, as seen in the provided example, will result in unsatisfactory results.
The Solution
Fortunately, a custom function can be created to extend the functionality of strpos and accommodate arrays of needles. The following code snippet, inspired by contributions from the PHP community, provides a solution:
function strposa(string $haystack, array $needles, int $offset = 0): bool { foreach($needles as $needle) { if(strpos($haystack, $needle, $offset) !== false) { return true; // stop on first true result } } return false; }
Usage
To utilize this function, you can pass the haystack string, the array of needles, and an optional offset as parameters. For example:
$string = 'This string contains word "cheese" and "tea".'; $array = ['burger', 'melon', 'cheese', 'milk']; var_dump(strposa($string, $array)); // will return true, since "cheese" has been found
This will search the string for the presence of any of the needles in the array. If any needle is found, the function will return true, stopping further iteration.
The above is the detailed content of How Can I Efficiently Search a String for Multiple Substrings Using PHP?. For more information, please follow other related articles on the PHP Chinese website!