-1

我有一个充满单词的数组:

$words = array("word", "word2", "apple", "cake");

然后我想在一个函数中使用这个数组,该函数将检查字符串($text)中是否存在一个单词,就像这样......

function find_word($text) {
    $words = array("word", "word2", "apple", "cake");
}

...但我希望函数停止检查单词是否存在并在数组中第一次出现单词后返回true ,在字符串 ($text) 中。(因此该函数不必根据字符串检查每个单词。)如果找不到该单词,那么我希望它返回 false。

我试过搜索一些方法,我能找到的唯一东西是使用的方法preg_match,但他们检查了数组中的每个单词与字符串,我认为这会减慢脚本的速度。

实现这一目标的最佳方法是什么?

注意:即使数组中的单词之一在单词中,我也希望此函数返回 true。例如:blahAPPLErandom应该返回true,因为apple在里面。

4

2 回答 2

1
for ($i = 0; $i < count($words); $i++)
    if (stripos($text, $words[$i]) !== false)
        return true;
于 2013-09-01T14:14:57.710 回答
0

使用 stristr PHP 函数怎么样?

function find_word($text) {
    $words = array("word", "word2", "apple", "cake");
    foreach ($words as $w) {
        if (stristr($text, $w)) return True;
    }
    return False;
}
于 2013-09-01T14:20:26.890 回答