匹配一个不是特定单词的 3 个或更多字母单词
Match a word that's 3 or more letter words that's not a certain word
我需要匹配 "do you" 之后任何 3 个或更多字母的单词,这不是单词 "lie",但是当我尝试少于 3 个单词时,它不能正常工作。我该如何解决这个问题?
$text = "do you a";
if (preg_match("~(do you) (?!lie){3,}~", $text)) { echo "it matched!"; }
当它不匹配时它回显了 "it matched"。
您的模式不正确。您不能将量词应用于负面的前瞻模式,必须像这样编写您的模式,
(do you) (?!lie\b)[a-zA-Z]{3,}
此外,您应该使用单词边界 \b
使其不只匹配 lie
而是匹配其他单词,例如 lied
$text = "do you a";
if (preg_match("~(do you) (?!lie\b)[a-zA-Z]{3,}~", $text)) { echo "it matched! ".$text; }
$text = "do you lie";
if (preg_match("~(do you) (?!lie\b)[a-zA-Z]{3,}~", $text)) { echo "it matched! ".$text; }
$text = "do you lied";
if (preg_match("~(do you) (?!lie\b)[a-zA-Z]{3,}~", $text)) { echo "it matched! ".$text; }
只打印这个,
it matched! do you lied
非正则版本是将 do you
和 space 上的句子展开并查看 do you
之后的单词然后确保它是一个字符串,超过三个字符并且不是 "lie".
$text = "John do you know a lie";
$after = explode(" ", explode("do you ", $text)[1])[0];
echo $after;
if(strlen($after) >=3 && is_string($after) && strtolower($after) != "lie"){
echo "true";
}else{
echo "false";
}
如果字符串并不总是包含 do you
那么您需要在第一次展开后检查数组是否有第二个项目。
否则它将 return 通知,未定义 [1]。
$text = "John do know a lie";
$temp = explode("do you ", $text);
if(isset($temp[1])){
$after = explode(" ", $temp[1])[0];
}else{
$after = null;
}
echo $after;
if(strlen($after) >=3 && is_string($after) && strtolower($after) != "lie"){
echo "true";
}else{
echo "false";
}
我需要匹配 "do you" 之后任何 3 个或更多字母的单词,这不是单词 "lie",但是当我尝试少于 3 个单词时,它不能正常工作。我该如何解决这个问题?
$text = "do you a";
if (preg_match("~(do you) (?!lie){3,}~", $text)) { echo "it matched!"; }
当它不匹配时它回显了 "it matched"。
您的模式不正确。您不能将量词应用于负面的前瞻模式,必须像这样编写您的模式,
(do you) (?!lie\b)[a-zA-Z]{3,}
此外,您应该使用单词边界 \b
使其不只匹配 lie
而是匹配其他单词,例如 lied
$text = "do you a";
if (preg_match("~(do you) (?!lie\b)[a-zA-Z]{3,}~", $text)) { echo "it matched! ".$text; }
$text = "do you lie";
if (preg_match("~(do you) (?!lie\b)[a-zA-Z]{3,}~", $text)) { echo "it matched! ".$text; }
$text = "do you lied";
if (preg_match("~(do you) (?!lie\b)[a-zA-Z]{3,}~", $text)) { echo "it matched! ".$text; }
只打印这个,
it matched! do you lied
非正则版本是将 do you
和 space 上的句子展开并查看 do you
之后的单词然后确保它是一个字符串,超过三个字符并且不是 "lie".
$text = "John do you know a lie";
$after = explode(" ", explode("do you ", $text)[1])[0];
echo $after;
if(strlen($after) >=3 && is_string($after) && strtolower($after) != "lie"){
echo "true";
}else{
echo "false";
}
如果字符串并不总是包含 do you
那么您需要在第一次展开后检查数组是否有第二个项目。
否则它将 return 通知,未定义 [1]。
$text = "John do know a lie";
$temp = explode("do you ", $text);
if(isset($temp[1])){
$after = explode(" ", $temp[1])[0];
}else{
$after = null;
}
echo $after;
if(strlen($after) >=3 && is_string($after) && strtolower($after) != "lie"){
echo "true";
}else{
echo "false";
}