PHP Regex match sentences -
this question has answer here:
- php string replace match whole word 2 answers
i trying compare 2 sentences using php , regex this:
$data = "i happy man 2 kids"; if (preg_match('/^(?=.*i)(?=.*am)(?=.*happy)(?=.*with)(?=.*2)(?=.*kids)/i', $data)) {echo 'match';} else {echo 'not match';} and seems work fine, if change sentence to:
$data = "i happy man 20 kids"; if (preg_match('/^(?=.*i)(?=.*am)(?=.*happy)(?=.*with)(?=.*2)(?=.*kids)/i', $data)) {echo 'match';} else {echo 'not match';} it's still saying matches. problem is not matching exact number , checking if theres number 2 on other sentence.
add word boundaries:
$data = "i happy man 20 kids"; if (preg_match('/^(?=.*i)(?=.*am)(?=.*happy)(?=.*with)(?=.*\b2\b)(?=.*kids)/i', $data)) { // here ___^^ ^^ echo 'match'; } else { echo 'not match'; } you may want add in each lookahead, regex become unredable
$data = "i happy man 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'; }
Comments
Post a Comment