Home > Backend Development > PHP Tutorial > How to Check if a String Contains Any Array Element (Case-Insensitive)?

How to Check if a String Contains Any Array Element (Case-Insensitive)?

Susan Sarandon
Release: 2024-11-14 17:47:02
Original
385 people have browsed it

How to Check if a String Contains Any Array Element (Case-Insensitive)?

Searching for Array Items within a String (Case Insensitive)

In various programming scenarios, it may be necessary to determine whether a given string contains any of the elements specified in an array. This task can be particularly challenging when case insensitivity is required.

To address this, we can leverage a custom PHP function named contains(). This function efficiently checks if a string ($str) contains any of the items ($arr) present in an array:

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

The stripos() function used within the loop performs a case-insensitive search for the array element within the string. If any match is found, the function returns true; otherwise, it returns false, indicating that the string doesn't contain any of the specified array elements.

For example, consider the following code snippet:

$string = 'My nAmE is Tom.';
$array = array("name","tom");
if(contains($string,$array))
{
    // The string contains at least one element from the array, so do something.
}
Copy after login

The contains() function iterates through each element in the array, performing a case-insensitive search. In this example, the string contains the element "name," which satisfies the condition. As a result, the if statement will be executed, and any desired action can be performed.

By employing this custom function, programmers can efficiently determine whether a string contains any items from an array, regardless of case sensitivity.

The above is the detailed content of How to Check if a String Contains Any Array Element (Case-Insensitive)?. 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