2

I am trying to compare two sentences using PHP and regex like this:

$data = "I am a happy man with 2 kids";
if (preg_match('/^(?=.*I)(?=.*am)(?=.*happy)(?=.*with)(?=.*2)(?=.*kids)/i', $data)) {echo 'match';} else {echo 'not match';}

and that seems to work fine, but if I change the sentence to:

$data = "I am a happy man with 20 kids";
if (preg_match('/^(?=.*I)(?=.*am)(?=.*happy)(?=.*with)(?=.*2)(?=.*kids)/i', $data)) {echo 'match';} else {echo 'not match';}

It's still saying that matches. The problem is that is not matching the exact number and just checking if theres a number 2 on the other sentence.

Roots
  • 210
  • 1
  • 10

1 Answers1

4

Add word boundaries:

$data = "I am a happy man with 20 kids";
if (preg_match('/^(?=.*I)(?=.*am)(?=.*happy)(?=.*with)(?=.*\b2\b)(?=.*kids)/i', $data)) {
//                                                 here ___^^ ^^
    echo 'match';
} else {
    echo 'not match';
}

You may want to add also in each lookahead, but the regex will become unredable

$data = "I am a happy man with 20 kids";
if (preg_match('/^(?=.*\bI\b)(?=.*\bam\b)(?=.*\bhappy\b)(?=.*\bwith\b)(?=.*\b2\b)(?=.*\bkids\b)/i', $data)) {
    echo 'match';
} else {
    echo 'not match';
}
Toto
  • 89,455
  • 62
  • 89
  • 125