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

How to Efficiently Check for Element Presence in a String?

DDD
Release: 2024-11-15 19:54:03
Original
1045 people have browsed it

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

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

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

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!

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