In PHP, strpos is a commonly used function to search for the first occurrence of a substring within a given string. While it is capable of finding a single substring, there may be situations where you need to search for multiple substrings simultaneously.
In your specific example, you want to check whether all the elements in the $find_letters array exist within the $string variable. However, directly passing an array as the needle to strpos will not work as it expects a single value.
To address this, you can utilize a custom function that performs the task you need. Here's an updated version of the function provided as the answer:
function strposa(string $haystack, array $needles, int $offset = 0): bool { foreach ($needles as $needle) { if (strpos($haystack, $needle, $offset) !== false) { return true; // Stop on the first true result } } return false; }
In this function, we iterate through each element in the $needles array. For each element, we use strpos to check if it exists within the $haystack string, starting from the specified $offset position. If any of the elements matches, we return true immediately, indicating that the search is successful.
Usage example:
$string = 'This string contains word "cheese" and "tea".'; $array = ['burger', 'melon', 'cheese', 'milk']; if (strposa($string, $array)) { echo 'true'; } else { echo 'false'; }
Output:
true
In this example, the function returns true because the string contains one of the elements in the array, namely "cheese."
The above is the detailed content of How Can I Efficiently Check for Multiple Substrings in a PHP String?. For more information, please follow other related articles on the PHP Chinese website!