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

DDD
Release: 2024-11-27 11:59:13
Original
610 people have browsed it

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

strpos with Arrays: A Deeper Dive

In PHP, the strpos function searches for a string within another string. Often, we encounter situations where we want to search for multiple strings simultaneously. While the provided code fails to perform this task, we can explore alternative solutions using an array of search terms.

Custom Function for Array Needles

One approach is to create a custom function that mimics the functionality of strpos for an array of needles:

function strposa($haystack, $needles=array(), $offset=0) {
    $chr = array();
    foreach($needles as $needle) {
        $res = strpos($haystack, $needle, $offset);
        if ($res !== false) $chr[$needle] = $res;
    }
    if(empty($chr)) return false;
    return min($chr);
}
Copy after login

This function takes a haystack string, an array of needles to search for, and an optional offset. It returns the index of the first occurrence of any of the needles, or false if none are found.

Improved Custom Function

To enhance this function, we can stop the search once the first needle is found:

function strposa(string $haystack, array $needles, int $offset = 0): bool {
    foreach($needles as $needle) {
        if(strpos($haystack, $needle, $offset) !== false) {
            return true; 
        }
    }
    return false;
}
Copy after login

This updated function scans the haystack for each needle in the array and returns true as soon as it finds a match. It's more efficient when multiple needles may be present in the haystack.

Usage Examples

To use these functions, simply pass the haystack string and the array of needles as arguments.

$string = 'This string contains word "cheese" and "tea".';
$array = ['burger', 'melon', 'cheese', 'milk'];

if(strposa($string, $array)) {
    echo 'true'; // since "cheese" is found
}
Copy after login

In this example, the script outputs true because "cheese" is a substring of the haystack.

The above is the detailed content of How Can I Efficiently Search for Multiple Substrings within a String in PHP Using Arrays?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template