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

How Can I Efficiently Search a String for Multiple Substrings Using PHP?

Susan Sarandon
Release: 2024-12-15 03:15:10
Original
978 people have browsed it

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

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

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!

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