Boomfelled
Boomfelled

Reputation: 535

Comparing two strings using preg_match

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

Answers (4)

anik4e
anik4e

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

akond
akond

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

lxg
lxg

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

Cleiton Souza
Cleiton Souza

Reputation: 881

The correct : implode("|", $array)

Cause | = OR

Upvotes: 1

Related Questions