Search code examples
phpregexpreg-match-allword-boundary

Preg_match_all exact match with multiple words


I have a long list of keywords represented below with the variable $skills which contains Shop Supervisor but not Machine Shop Supervisor:

$text = "Machine Shop Supervisor";
preg_match_all("~\b$skills\b~i", $text, $matchWords);
foreach ($matchWords[0] as $matchWord) {
     echo "<b>MatchWord:</b> " . $matchWord.  "<br>";
 }

Results: Shop Supervisor

How can I get the exact match of $text? so in this case there shouldn't be any results as Machine Shop Supervisor is not in the keywords list.

Thanks.


Solution

  • You should use anchors, not word boundaries, so it is a full string match.

    preg_match_all("~^$skills$~i", $text, $matchWords);
    

    A space is a non-word character so it matched.

    https://3v4l.org/OYlfD