Home  >  Article  >  Backend Development  >  How to Efficiently Check for Element Presence in a String?

How to Efficiently Check for Element Presence in a String?

DDD
DDDOriginal
2024-11-15 19:54:03951browse

How to Efficiently Check for Element Presence in a String?

Efficiently Checking for Element Presence in a String

Determining whether a string contains any item from an array is a common programming scenario. While standard programming languages may lack built-in functions for this specific task, it is relatively straightforward to create a custom function to achieve this functionality.

Consider the example:

$string = 'My nAmE is Tom.';
$array = array("name","tom");

To check if the string contains any of the items in the array, a contains() function can be defined:

function contains($str, array $arr)
{
    foreach($arr as $a) {
        if (stripos($str,$a) !== false) return true;
    }
    return false;
}

This function iterates through the array's elements, performing a case-insensitive search for each element within the string using stripos(). If any matching element is found in the string, the function returns true, indicating its presence. Otherwise, it returns false.

By using this custom function, we can efficiently check whether the provided string contains any of the items in the array, as demonstrated in the following usage:

if(contains($string,$array))
{
    // do something to indicate the presence of an item
}

The above is the detailed content of How to Efficiently Check for Element Presence in a String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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