regex match if string contain all the words or a condition

后端 未结 2 978
轻奢々
轻奢々 2021-02-10 21:10

im making a simple word game with php and regex, how can we search that if a string have to require two or more words?

lets say

\"cat\"
\"dog\"
\"play\"          


        
相关标签:
2条回答
  • 2021-02-10 21:17

    The regex you're looking for is:

    /(?=.*?\bcat\b)(?=.*?\bdog\b)(?=(.*?\bplay\b){2})^.*$/
    

    Explanation: I believe words cat, dog and play (twice) can appear in the text in any order but they must all be present in the sentence to qualify. Above regex is using positive lookahead to make sure the presence of above conditions.

    Here is the online working demo of above RegEx

    0 讨论(0)
  • 2021-02-10 21:37

    Try preg_match_all(/cat.+dog(.+play){2}/i,$str,$out);

    0 讨论(0)
提交回复
热议问题