Utilitarian Strpos and Array-based Needle Searches
When searching for multiple strings within a string, the built-in PHP function strpos may not suffice. To address this, a snippet from php.net proposes a custom function, strposa, that efficiently finds the first occurrence of any string from a given array within a specified string.
Implementation of strposa
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 Example
Consider the string:
$string = 'Whis string contains word "cheese" and "tea".';
And an array of strings:
$array = ['burger', 'melon', 'cheese', 'milk'];
Using strposa:
if (strposa($string, $array, 1)) { echo 'true'; } else { echo 'false'; }
This will output true because the string contains a needle from the array, namely "cheese".
Improved strposa
An updated version of strposa optimizes performance by terminating the search upon the first needle match. This enhances efficiency when searching for multiple needles in a haystack.
The above is the detailed content of Is strposa a More Efficient Alternative to strpos for Multiple String Searches in PHP?. For more information, please follow other related articles on the PHP Chinese website!