Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Check if array element exists in any part of the string

Tags:

php

I know how to find if your string equals an array value:

$colors = array("blue","red","white");

$string = "white";

if (!in_array($string, $colors)) {
    echo 'not found';
}

...but how do I find if the string CONTAINS any part of the array values?

$colors = array("blue","red","white");

$string = "whitewash"; // I want this to be found in the array

if (!in_array($string, $colors)) {
    echo 'not found';
}
like image 505
php die Avatar asked Feb 12 '23 07:02

php die


1 Answers

Or in one shot:

if( preg_match("(".implode("|",array_map("preg_quote",$colors)).")",$string,$m)) {
    echo "Found ".$m[0]."!";
}

This can also be expanded to only allow words that start with an item from your array:

if( preg_match("(\b(?:".implode("|",array_map("preg_quote",$colors))."))",$string,$m)) {

Or case-insensitive:

if( preg_match("(".implode("|",array_map("preg_quote",$colors)).")i",$string,$m)) {

CI with starting only:

if( preg_match("(\b(?:".implode("|",array_map("preg_quote",$colors))."))i",$string,$m)) {

Or anything really ;)

like image 156
Niet the Dark Absol Avatar answered Feb 15 '23 09:02

Niet the Dark Absol