在字符串中搜索单词


Searching for words in a string

在php中搜索字符串并找到不区分大小写的匹配的最佳方法是什么?

例如:

$SearchString = "This is a test";

从这个字符串中,我想找到单词test,或test或test。

谢谢!

编辑我还应该提到我想要搜索字符串,如果它包含黑名单数组中的任何单词,则停止处理它。因此,"Test"的精确匹配是很重要的,然而,情况不是

如果你想查找单词,并且想要禁止"FU"而不是"fun",你可以使用正则表达式whit_b,其中'b标记单词的开始和结束,所以如果你搜索"'bfu'b"如果不匹配"fun"如果在分隔符后面添加"i",则其搜索大小写不敏感,如果你有一个像"fu"foo"bar"这样的单词列表,你的模式可以是这样的:"#'b(fu|foo|bar)'b#i",或者你可以使用一个变量:

if(preg_match("#'b{$needle}'b#i", $haystack))
{
   return FALSE;
}

编辑,根据注释中的要求添加了多字字符转义示例:

/* load the list somewhere */
$stopWords = array( "word1", "word2" );
/* escape special characters */
foreach($stopWords as $row_nr => $current_word)
{
    $stopWords[$row_nr] = addcslashes($current_word, '['^$.|?*+()');
}
/* create a pattern of all words (using @ insted of # as # can be used in urls) */
$pattern = "@'b(" . implode('|', $stopWords) . ")'b@";
/* execute the search */
if(!preg_match($pattern, $images))
{
    /* no stop words */
}

您可以使用以下几种方法之一,但我倾向于使用其中一种:

可以使用stripos()

if (stripos($searchString,'test') !== FALSE) {
  echo 'I found it!';
}

您可以将字符串转换为特定的大小写,并使用strpos()

进行搜索。
if (strpos(strtolower($searchString),'test') !== FALSE) {
  echo 'I found it!';
}

我两者都做,没有偏好——一个可能比另一个更有效(我怀疑第一个更好),但我实际上不知道。

作为一些更可怕的例子,你可以:

  • 使用i修饰符
  • 的正则表达式
  • Do if (count(explode('test',strtolower($searchString))) > 1)

stripos,我想。假设它在找到匹配项时停止搜索,并且我猜它在内部会转换为小写(或大写),所以这是您所能得到的最好结果。

http://us3.php.net/manual/en/function.preg-match.php

取决于你是否想匹配

在这种情况下,你可以这样做:

$SearchString= "This is a test";
$pattern = '/[Test|TEST]/';
preg_match($pattern, $SearchString);

我没有正确阅读问题。正如在其他答案中所述,stripos或preg_match函数将完全满足您的要求。

我最初提供了stristr函数作为答案,但如果你只是想在另一个字符串中找到一个字符串,你实际上不应该使用这个,因为它除了搜索参数之外还返回字符串的其余部分。