如何检查一个单词在句子中是否存在


How to check if a word exists in a sentence

例如,如果我的句子是$sent = 'how are you';,如果我使用strstr($sent, $key)搜索$key = 'ho',它将返回true,因为我的句子中有ho

我在寻找的是一种方法,如果我只搜索如何,是或你返回真。我该怎么做呢?

您可以使用preg-match函数,该函数使用带有单词边界的正则表达式:

if(preg_match('/'byou'b/', $input)) {
  echo $input.' has the word you';
}

如果您想要检查同一字符串中的多个单词,并且您正在处理大字符串,那么这个更快:

$text = explode(' ',$text);
$text = array_flip($text);

然后你可以用:

检查单词
if (isset($text[$word])) doSomething();

这个方法快如闪电。

但是要检查短字符串中的几个单词,则使用preg_match.

更新:

如果你真的要使用这个,我建议你像这样实现它,以避免问题:

$text = preg_replace('/[^a-z's]/', '', strtolower($text));
$text = preg_split('/'s+/', $text, NULL, PREG_SPLIT_NO_EMPTY);
$text = array_flip($text);
$word = strtolower($word);
if (isset($text[$word])) doSomething();

那么双空格、换行、标点和大写字母就不会产生假阴性。

此方法在检查大字符串(即整个文本文档)中的多个单词时要快得多,但如果您想做的只是查找单个单词是否存在于正常大小的字符串中,则使用preg_match更有效。

你可以做的一件事是用空格将句子分成一个数组。

首先,您需要删除任何不需要的标点符号。下面的代码删除了所有不是字母、数字或空格的内容:

$sent = preg_replace("/[^a-zA-Z 0-9]+/", " ", $sent);

现在,你所有的是单词,由空格分隔。创建一个按空格分隔的数组

$sent_split = explode(" ", $sent);

最后,您可以进行检查。以下是所有步骤的组合。

// The information you give
$sent = 'how are you';
$key  = 'ho';
// Isolate only words and spaces
$sent = preg_replace("/[^a-zA-Z 0-9]+/", " ", $sent);
$sent_split = explode(" ", $sent);
// Do the check
if (in_array($key, $sent))
{
    echo "Word found";
}
else
{
    echo "Word not found";
}
// Outputs: Word not found
//  because 'ho' isn't a word in 'how are you'

@codaddict的答案在技术上是正确的,但如果您正在搜索的单词是由用户提供的,则需要转义搜索词中具有特殊正则表达式含义的任何字符。例如:

$searchWord = $_GET['search'];
$searchWord = preg_quote($searchWord);
if (preg_match("/'b$searchWord'b", $input) {
  echo "$input has the word $searchWord";
}

对Abhi的回答表示认可,我有几个建议:

  1. 我将/I添加到正则表达式中,因为句子单词可能不区分大小写
  2. 我在基于文档preg_match返回值的比较中添加了显式=== 1

    $needle = preg_quote($needle);
    return preg_match("/'b$needle'b/i", $haystack) === 1;