在PHP中查找变量字符串中的确切单词
我试图在字符串中找到一个精确的单词 例如:在PHP中查找变量字符串中的确切单词,php,strpos,Php,Strpos,我试图在字符串中找到一个精确的单词 例如: $word = "Many Blocks"; if (strpos($word, "Block")){ echo "You found 1 Block"; } if (strpos($word, "Blocks")){ echo "You found many Blocks"; } 这里的问题是如果两者都是真的。。我只需要找到如果是同一个词..你可以用regex这样做: if(preg_match("/Block(\s|$|\.|\,)/
$word = "Many Blocks";
if (strpos($word, "Block")){
echo "You found 1 Block";
}
if (strpos($word, "Blocks")){
echo "You found many Blocks";
}
这里的问题是如果两者都是真的。。我只需要找到如果是同一个词..你可以用regex这样做:
if(preg_match("/Block(\s|$|\.|\,)/", $string))
这将查找单词“Block”,后跟空格、点、逗号或字符串结尾。您可以使用regex这样做:
if(preg_match("/Block(\s|$|\.|\,)/", $string))
这将查找单词“Block”,后跟空格、点、逗号或字符串结尾。正如Jay Blanchard所说,您需要以以下方式使用正则表达式:--
正如Jay Blanchard所说,您需要以以下方式使用regex:--
您的代码将在第二次搜索时使用偏移量和一些其他更改
$result = 'You found no blocks';
$position = strpos($word, "Block");
if ($position !== false){
$result = "You found 1 Block";
if (strpos($word, "Blocks",$position + 1)){
$result = "You found many Blocks";
}
}
echo $result;
通过使用strpos()偏移量,您可以不断循环,直到找不到该单词。 $found = 0;
$offset = 0;
while(true){
$position = strpos($word,'Block',$offset );
if ($position === false){break;}
$found++;
$offset = $position + 1; // set offset just beyond the current found word
}
echo "Found: $found";
或
这一条代码很简单,但速度较慢:
preg_match_all('/Blocks/',$word,$matches);
$found = count($matches[1]);
您的代码将在第二次搜索时使用偏移量和一些其他更改
$result = 'You found no blocks';
$position = strpos($word, "Block");
if ($position !== false){
$result = "You found 1 Block";
if (strpos($word, "Blocks",$position + 1)){
$result = "You found many Blocks";
}
}
echo $result;
通过使用strpos()偏移量,您可以不断循环,直到找不到该单词。 $found = 0;
$offset = 0;
while(true){
$position = strpos($word,'Block',$offset );
if ($position === false){break;}
$found++;
$offset = $position + 1; // set offset just beyond the current found word
}
echo "Found: $found";
或
这一条代码很简单,但速度较慢:
preg_match_all('/Blocks/',$word,$matches);
$found = count($matches[1]);
你应该用正则表达式。我不知道Reggie有一个前Sam-@Jayblanchard你们这些家伙很可爱。“我只需要找到是否是同一个词”-同一个词,或者完全匹配?很难说你所说的“同一个词”是什么意思。事实。你应该用regex来做这个。我不知道Reggie有一个前Sam-@jayblanchard,你们真可爱。“我需要找到的是同一个词-,同一个词,还是完全匹配?很难说你所说的“同一个词”是什么意思。事实。这是一个很好的答案开始,但OP需要同时搜索两个。这是一个很好的答案开始,但OP需要同时搜索两个。这就是我计划提出的,但OP的问题对我的口味来说现在有点不清楚。非常感谢,preg_match会解决这个问题。。谢谢欢迎所有投赞成票的人,你可能得到了答案。是的!对不起,我不能给你投票,因为我太新了。没问题,解决问题很酷。这就是我计划提出的,但OP的问题对我来说现在有点不清楚。非常感谢你,preg_match会解决问题的。。谢谢欢迎所有投赞成票的人,你可能得到了答案。是的!对不起,我不能给你投票,因为我太新了。没问题,解决问题很酷。@JayBlanchard我有点慢,但我最终到达那里。@JayBlanchard我有点慢,但我最终到达那里。