Home > Backend Development > PHP Tutorial > 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
Release: 2024-11-20 17:36:22
Original
674 people have browsed it

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

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

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!

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