在 PHP 的 var 字符串中找到确切的单词
find exact word in a var string in PHP
我正在尝试在字符串中找到一个确切的词。
示例:
$word = "Many Blocks";
if (strpos($word, "Block")){
echo "You found 1 Block";
}
if (strpos($word, "Blocks")){
echo "You found many Blocks";
}
这里的问题是 if 都是 true.. 而我只需要找到 if 是同一个词..
您可以像这样使用正则表达式来做到这一点:
if(preg_match("/Block(\s|$|\.|\,)/", $string))
这将查找单词 "Block" 后跟 space 或点或逗号或字符串结尾。
正如 Jay Blanchard 所说,您需要按照以下方式使用正则表达式进行操作:--
$word = "Many Blocks";
if ( preg_match("~\bBlocks\b~",$word) )
echo "matched";
else
echo "no match";
您的代码可以在第二次搜索时使用偏移量并进行一些其他更改。
$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]);
我正在尝试在字符串中找到一个确切的词。
示例:
$word = "Many Blocks";
if (strpos($word, "Block")){
echo "You found 1 Block";
}
if (strpos($word, "Blocks")){
echo "You found many Blocks";
}
这里的问题是 if 都是 true.. 而我只需要找到 if 是同一个词..
您可以像这样使用正则表达式来做到这一点:
if(preg_match("/Block(\s|$|\.|\,)/", $string))
这将查找单词 "Block" 后跟 space 或点或逗号或字符串结尾。
正如 Jay Blanchard 所说,您需要按照以下方式使用正则表达式进行操作:--
$word = "Many Blocks";
if ( preg_match("~\bBlocks\b~",$word) )
echo "matched";
else
echo "no match";
您的代码可以在第二次搜索时使用偏移量并进行一些其他更改。
$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]);