Home > Backend Development > PHP Tutorial > 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
Release: 2024-10-24 18:28:19
Original
1103 people have browsed it

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

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

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!

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