【问题标题】:PHP return true in a function after first word is found找到第一个单词后,PHP在函数中返回true
【发布时间】:2013-09-01 14:12:36
【问题描述】:

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

$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 在那里。

【问题讨论】:

    标签: php regex arrays string search


    【解决方案1】:
    for ($i = 0; $i < count($words); $i++)
        if (stripos($text, $words[$i]) !== false)
            return true;
    

    【讨论】:

    • 我认为应该是 stripos 不区分大小写,根据 OP 的 blahAPPLErandom - APPLEapple 不会被同等对待。
    【解决方案2】:

    使用 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-12-30
      • 1970-01-01
      • 1970-01-01
      • 2016-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-10
      • 1970-01-01
      相关资源
      最近更新 更多