5

例如,如果我的句子是$sent = 'how are you';并且如果我搜索$key = 'ho'usingstrstr($sent, $key)它会返回true,因为我的句子ho中有。

如果我只搜索如何、是或你,我正在寻找的是一种返回 true 的方法。我怎样才能做到这一点?

4

5 回答 5

8

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

if(preg_match('/\byou\b/', $input)) {
  echo $input.' has the word you';
}
于 2011-11-10T04:50:40.110 回答
6

If you want to check for multiple words in the same string, and you're dealing with large strings, then this is faster:

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

Then you can check for words with:

if (isset($text[$word])) doSomething();

This method is lightning fast.

But for checking for a couple of words in short strings then use preg_match.

UPDATE:

If you're actually going to use this I suggest you implement it like this to avoid problems:

$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();

Then double spaces, linebreaks, punctuation and capitals won't produce false negatives.

This method is much faster in checking for multiple words in large strings (i.e. entire documents of text), but it is more efficient to use preg_match if all you want to do is find if a single word exists in a normal size string.

于 2011-11-10T04:57:31.980 回答
3

您可以做的一件事是按空格将句子分成数组。

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

$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'
于 2011-11-10T05:03:03.523 回答
1

@codaddict's answer is technically correct but if the word you are searching for is provided by the user, you need to escape any characters with special regular expression meaning in the search word. For example:

$searchWord = $_GET['search'];
$searchWord = preg_quote($searchWord);

if (preg_match("/\b$searchWord\b", $input) {
  echo "$input has the word $searchWord";
}
于 2011-11-10T04:55:12.050 回答
0

随着对 Abhi 的回答的认可,提出了一些建议:

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

    $needle = preg_quote($needle);
    return preg_match("/\b$needle\b/i", $haystack) === 1;
    
于 2012-12-17T10:23:14.113 回答