user3160596
user3160596

Reputation: 85

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?

Upvotes: 6

Views: 15909

Answers (2)

revo
revo

Reputation: 48711

$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

Upvotes: 5

Toto
Toto

Reputation: 91385

Use a quantifier:

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

and escape the ? ==> \?

Upvotes: 8

Related Questions