Is strposa a More Efficient Alternative to strpos for Multiple String Searches in PHP?

Patricia Arquette
Release: 2024-11-25 17:33:15
Original
117 people have browsed it

Is strposa a More Efficient Alternative to strpos for Multiple String Searches in PHP?

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

Usage Example

Consider the string:

$string  = 'Whis string contains word "cheese" and "tea".';
Copy after login

And an array of strings:

$array  = ['burger', 'melon', 'cheese', 'milk'];
Copy after login

Using strposa:

if (strposa($string, $array, 1)) {
    echo 'true';
} else {
    echo 'false';
}
Copy after login

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!

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