Reputation: 145
I'm fairly new to PHP and struggling to understand the best way to do this. I have an array:
$colours= array('Yellow', 'Red', 'Blue');
I now need to check a string against this array and if one of the colors exists in the string we then need to output the result into a new variable. Here's a sample string:
$string= "Black & Aztec Blue";
So in this case the desired output would be "Blue". Or, as suggested below both values could be saved in a second array? Has anyone done something like this before?
All help appreciated.
Upvotes: 2
Views: 126
Reputation: 780818
Create a regexp that matches any of the words using alternation |
.
$regexp = '/\b(' . implode('|', $colours) . ')\b/'; // $regexp = '/\b(Yellow|Red|Blue)\b/'
if (preg_match($regexp, $string, $match)) {
$found_word = $match[0];
}
\b
matches word boundaries, so this will not match if the strings are adjacent like BlackBlue
. Take them out if you want to match the colours in this case.
Upvotes: 2