Home > Backend Development > PHP Tutorial > How Can I Efficiently Check for Multiple Substrings in a PHP String?

How Can I Efficiently Check for Multiple Substrings in a PHP String?

Linda Hamilton
Release: 2024-11-27 13:17:16
Original
774 people have browsed it

How Can I Efficiently Check for Multiple Substrings in a PHP String?

Finding Multiple Substrings Using strpos and Arrays

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;
}
Copy after login

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';
}
Copy after login

Output:

true
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template