简体   繁体   中英

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

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 hometown?
do you want to eat teloq at my hometown?
do you want to eat tempeyek at my hometown?
do you want to eat karipap at my hometown?

How do I create a pattern in regex that will match the above pattern? Like this:

do you want to eat * at my hometown?

Asterik (*) means any word. Here is the regex pattern that I have so far:

$text = "do you want to eat meatball at my hometown?";
$pattern = "/do you want to eat ([a-zA-Z0-9]) at my hometown?/i";

if (preg_match($pattern, $text)) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}

The ([a-zA-Z0-9]) format is not matching on word. How do I match a string on a word?

Use a quantifier:

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

and escape the ? ==> \\?

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM