Home  >  Article  >  Backend Development  >  Does a String Contain Any Items From an Array (Case Insensitive)?

Does a String Contain Any Items From an Array (Case Insensitive)?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-20 17:36:22589browse

Does a String Contain Any Items From an Array (Case Insensitive)?

Checking if a String Contains Any Items from an Array (Case Insensitive)

In this programming challenge, we aim to determine whether a given string contains any of the items included in an provided array, disregarding case differences.

To address this, we can leverage the stripos() function in PHP. Here's an implementation:

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

Using this function, we can check if a string contains any of the items in an array as follows:

$str = 'My nAmE is Tom.';
$arr = ['name', 'tom'];
if (contains($str, $arr)) {
    // Do something to indicate that it contains
}

The above is the detailed content of Does a String Contain Any Items From an Array (Case Insensitive)?. 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