簡體   English   中英

如何在PHP中匹配字符串中的任何單詞與正則表達式

[英]How to match any word in a String with Regex in PHP

我有這些字符串。 我想要一個正則表達式來匹配它們,並在我將它們傳遞給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])格式與單詞不匹配。 如何匹配單詞上的字符串?

使用量詞:

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

逃避? ==> \\?

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

(\\w+)匹配一個或多個單詞字符。

(?=\\sat)是一個積極的前瞻 ,它匹配一個空格\\s和字母at

正則表達式現場演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM