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.
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().
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!