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

柔情痞子 提交于 2019-12-20 01:35:09

问题


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?


回答1:


Use a quantifier:

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

and escape the ? ==> \?




回答2:


$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



来源:https://stackoverflow.com/questions/20922863/how-to-match-any-word-in-a-string-with-regex-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!