0

I have an array of matching words:

$search = array("lorem","dolor","sit");

And an array to search in:

 $results= array(
       "Lorem ipsum dolor sit amet, consectetur",
       "Ut enim ad minim veniam, quis nostrud exercitation"
       "Duis aute irure dolor in reprehenderit in voluptate velit esse"
       "Excepteur sint occaecat cupidatat non proident"
    );

Is there a regex to return true where two of given words are matching?

Trevor
  • 16,080
  • 9
  • 52
  • 83
Antonino Bonumore
  • 787
  • 1
  • 13
  • 27

2 Answers2

1

You could use a word boundary \b in your regular expression.

A word boundary is a position between \w and \W (non-word char), or at the beginning or end of a string if it begins or ends (respectively) with a word character.

So maybe something like this..

foreach ($results as $result) {
   $pattern = "/\b(" . implode('|', $search) . ")\b/i";
   $found   = preg_match_all($pattern, $result, $matches);

   if ($found) {
     print_r($matches[0]);
   }
}

Or you could do away with your search array and just use it as a regular expression:

foreach ($results as $result) {
   $found = preg_match_all("/\b(?:lorem|dolor|sit)\b/i", $result, $matches);
   if ($found) {
     print_r($matches[0]);
   }
}

Output:

Array
(
    [0] => Lorem
    [1] => dolor
    [2] => sit
)
Array
(
    [0] => dolor
)
hwnd
  • 69,796
  • 4
  • 95
  • 132
0

You can generate a regex to search by this

$regex = '/(' . implode('|', $search) . ')/i';

which will be:

/(lorem|dolor|sit)/i

The /i makes it caseless.

You can then use the return value of preg_match_all() to see the number of matched words.

tigrang
  • 6,767
  • 1
  • 20
  • 22