Build a regular expression by joining the terms of the array with |
, and adding an optional [-+]
at the beginning:
$names = array ("Blue", "Gold", "White", "Purple", "Green", "Teal", "Purple", "Red");
$drag = "Glowing looks to be +Blue.";
$pattern = '/[-+]?(' . join($names, '|') . ')/';
$matches = array();
preg_match($pattern, $drag, $matches);
$matches = $matches[0];
var_dump($matches);
Output:
string(5) "+Blue"
If you want to insure that you match only +Blue
and not +Bluebell
, you can add word boundary matches, \b
, to the beginning/end of the regex.
If you want to find all instances of all words, use preg_match_all
instead.