Home  >  Article  >  Backend Development  >  How to Check if a String Contains an Element from an Array in PHP?

How to Check if a String Contains an Element from an Array in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-10-24 18:28:19986browse

How to Check if a String Contains an Element from an Array in PHP?

Determine String Containment within Array

In PHP, the necessity often arises to ascertain whether a string encompasses any elements stored within an array. This scenario is encountered when verifying user-submitted data against an established list of values.

Implementation Considerations

Utilizing in_array() to perform this check may yield unexpected results, as it evaluates strict equality. An alternative approach involves iterating through the array elements and comparing them to the string using strstr(), stristr(), or strpos().

Code Example

Consider the following array of owned URLs:

$owned_urls = array('website1.com', 'website2.com', 'website3.com');

To check if a user-inputted string contains any of these URLs, implement the following code:

<code class="php">$string = 'my domain name is website3.com';
foreach ($owned_urls as $url) {
    if (strpos($string, $url) !== FALSE) {
        echo "Match found";
        return true;
    }
}
echo "Not found!";
return false;</code>

Stristr()orstripos()` should be used for case-insensitive comparisons.

The above is the detailed content of How to Check if a String Contains an Element from an Array in PHP?. 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