How to match any word in a String with Regex in PHP

后端 未结 2 1845
春和景丽
春和景丽 2021-01-18 23:53

I have these strings. I want a regular expression to match them and return true when I pass them to preg_match function.

do you want to eat katak at my home         


        
相关标签:
2条回答
  • 2021-01-19 00:35

    Use a quantifier:

    $pattern = "/do you want to eat ([a-z0-9]*) at my hometown\?/i";
    //                                here __^
    

    and escape the ? ==> \?

    0 讨论(0)
  • 2021-01-19 00:42
    $text = "do you want to eat meatball at my hometown?";
    $pattern = "/(\w+)(?=\sat)/";
    if (preg_match($pattern, $text))
    

    (\w+) matches one or more word characters.

    (?=\sat) is a positive lookahead that matches one whitespace \s and the letters at.

    Regex live demo

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