如何在PHP中匹配字符串中的任何单词与正则表达式

时间:2014-01-04 15:32:11

标签: php regex preg-match

我有这些字符串。我想要一个正则表达式来匹配它们,并在我将它们传递给preg_match函数时返回true。

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?

如何在正则表达式中创建与上述模式匹配的模式?像这样:

do you want to eat * at my hometown?

Asterik(*)表示任何单词。这是我到目前为止的正则表达式模式:

$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.";
}

([a-zA-Z0-9])格式与单词不匹配。如何匹配单词上的字符串?

2 个答案:

答案 0 :(得分:6)

使用量词:

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

并转义? ==> \?

答案 1 :(得分:3)

$text = "do you want to eat meatball at my hometown?";
$pattern = "/(\w+)(?=\sat)/";
if (preg_match($pattern, $text))

(\w+)匹配一个或多个单词字符。

(?=\sat)positive lookahead,匹配一个空格\s和字母at

Regex live demo