Reputation: 535
I would like to search $string for occurrences of the contents of $array but am having trouble with the implode function returning the following:
preg_match(): Delimiter must not be alphanumeric or backslash
So in the example below $string will be searched for 'Empire' or 'Jedi'.
This is almost certainly something to do with escaping but I can't get my head round it.
Many thanks
$string = 'The Empire Strikes back';
$array = array (
0 => 'Empire',
1 => 'Jedi'
);
if (preg_match( implode(" ", $array), $string )) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
Upvotes: 0
Views: 2462
Reputation: 493
You Can use this:
$Words = array('Empire', 'Jedi');
$strings = 'The Empire Strikes back';
foreach ($Words as $Word) {
if (preg_match("/\b$Word\b/", $strings)) {
echo "A match was found.";
}
else{
echo "A match was not found.";
}
}
Upvotes: 0
Reputation: 16035
$string = 'The Empire Strikes back';
$array = array (
0 => 'Empire',
1 => 'Jedi'
);
$re = join ('|', array_map('preg_quote', $array));
var_dump (preg_match ("/$re/", $string));
Upvotes: 1
Reputation: 13107
A regex must have delimiters. What you want is /Empire|Jedi/i
(read: “search for Empire or Jedi, case insensitive”).
Therefore, you must use it as follows:
...
preg_match('/' . implode("|", $array) . '/', $string)
...
Upvotes: 1