如果整个单词在字符串中,则使用PHP

如果整个单词在字符串中,则使用PHP,php,Php,在php中,如何检查字符串中是否存在整个单词?我在StackOverFlow上找到了一些答案: if (preg_match($needle, $haystack)) 另一种方式: if (strpos($haystack, $needle) !== false) 这两种方法都在一定程度上起作用,但如果$haystack只包含$Pionel的一部分,则这些方法也将返回true,这是一个问题 例如,如果我试图检查$haystack是否包含PartialWord,但我将$needle设置为Par

在php中,如何检查字符串中是否存在整个单词?我在StackOverFlow上找到了一些答案:

if (preg_match($needle, $haystack))
另一种方式:

if (strpos($haystack, $needle) !== false)
这两种方法都在一定程度上起作用,但如果$haystack只包含$Pionel的一部分,则这些方法也将返回true,这是一个问题

例如,如果我试图检查$haystack是否包含PartialWord,但我将$needle设置为Partial

$needle = "Partial";
$haystack = "PartialWord-random)exampletextfoo-blabla";
if (preg_match($needle, $haystack))
它将返回true,即使它应该返回false,因为$pinder等于Partial&要返回true,$pinder应该等于PartialWord


有什么建议吗?

最简单的解决方案是:

$words= preg_split("/\W/", $haystack);
return in_array($needle, $words);

其中\W是任何非单词字符。

最简单的解决方案是:

$words= preg_split("/\W/", $haystack);
return in_array($needle, $words);
preg_match('/\b(express\w+)\b/', $needle, $haystack); // matches expression
preg_match('/\b(\w*form\w*)\b/', $needle, $haystack); // matches perform,
                                                     // formation, unformatted
其中\W是任何非单词字符

preg_match('/\b(express\w+)\b/', $needle, $haystack); // matches expression
preg_match('/\b(\w*form\w*)\b/', $needle, $haystack); // matches perform,
                                                     // formation, unformatted
其中:

\b is a word boundary
\w+ is one or more "word" character*
\w* is zero or more "word" characters
有关PCRE,请参阅上的手册

其中:

\b is a word boundary
\w+ is one or more "word" character*
\w* is zero or more "word" characters

请参阅PCRE的手册。

我认为最简单的解决方案是使用preg\u match

If (preg_match("/\s" . $SearchWord . "\s/", $haystack)){
      Echo "found";
}else{
      Echo "not found";
}
它将查找$SearchWord,两边各有一个空格,这是我所知道的单词定义。
因此,在您的情况下,它将不匹配Partialword的Partial,因为Partialword中没有空格。

我认为最简单的解决方案是使用preg\u match

If (preg_match("/\s" . $SearchWord . "\s/", $haystack)){
      Echo "found";
}else{
      Echo "not found";
}
它将查找$SearchWord,两边各有一个空格,这是我所知道的单词定义。
所以在你的例子中,它不会匹配Partialword的Partial,因为Partialword中没有空格。

但是你的strign确实包含Partial,你的意思是你想搜索构成分词的东西,比如标点符号、空格等。然后是你的针,然后是构成分词的东西,比如标点符号,还是空白等?在这种情况下,请再次查看preg_match,但更改搜索表达式您确实放宽了单词的定义。但是您的strign确实包含部分字符。您的意思是您要搜索构成分词符的内容,如标点符号、空格等。然后是您的指针,然后是构成分词符的内容,比如标点符号,空格等等?在这种情况下,请再次查看preg_match,但更改搜索表达式。您在这里确实放宽了单词的定义。