Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if preg_match with multiple words

Tags:

php

Is it possible to use an if statement with preg_match for multiple words and to make the condition true if all words are found?

    $line = "one blah, two blah blah three";

    //not working code

    if (preg_match('[one|two|three]' , $line)) {
        echo "matched all three";
    }
    else{
        echo "didn't match all three";
    }

Have tried quite a few things but the conditional is always meet if even one word is found..

like image 418
Benjamin Avatar asked May 19 '15 04:05

Benjamin


1 Answers

Using positive lookahead:

preg_match("%(?=.*one)(?=.*two)(?=.*three)%", $line)

EDIT: Explanation: (?=...) says "match 0-length here if ... is immediately following". Thus, you can sketch it like this (with a bit different original line to demonstrate the out-of-order bit):

two blah, one blah blah three
----------=== found!
=== found!
------------------------===== found!

(where --- is .*, and === is the sought word). As each lookahead matches, the matched position is advanced by match size - but match size of a lookahead is always 0, so it stays in place (at the start of the string) and allows for the next lookahead to search the same space again.

like image 109
Amadan Avatar answered Sep 20 '22 22:09

Amadan