繁体   English   中英

使用正则表达式在String中找到单词的数组

[英]FInd array of words in String using regex

我正在寻找字符串中的一些单词,下面是我的代码

$str="Chup Raho Episode 5 by Ary Digital 16th September 2014";

$keywords=array('Ary digital','geo');

echo in_string($keywords,$str,'all');


function in_string($words, $string, $option)
{
if ($option == "all") {
    $isFound = true;
    foreach ($words as $value) {
        $isFound = $isFound && (stripos($string, $value) !== false); // returns boolean false if nothing is found, not 0
        if (!$isFound) break; // if a word wasn't found, there is no need to continue
    }
} else {
    $isFound = false;
    foreach ($words as $value) {
        $isFound = $isFound || (stripos($string, $value) !== false);
        if ($isFound) break; // if a word was found, there is no need to continue
    }
}
return $isFound;
}

该函数返回true或false,如果找到的单词返回1,否则返回0。我需要返回正在搜索的单词,因为我想在mysql中对该单词进行另一个搜索。 就像功能找到“ Ary digital”一样,它应该返回“ ary digital found”。 需要帮助。谢谢。

您可能想做这样的事情(未经测试):

preg_match('#(word1|word2|word3)#',$string,$matches);

然后,print_r($ matches)查看matchs数组的输出并获取您想要的位。 从那里您可以返回true / false等。

只需重写您已有​​的内容即可。 而不是返回布尔值,而是将匹配的关键字推送到一个新数组,然后返回该数组。

function in_string($keywords, $string, $searchAll = true) {
    $matches = array();
    foreach ($keywords as $keyword) {
        if (stripos($string, $keyword) !== false)
            array_push($matches, $keyword);
        if (!$searchAll)
            break;
    }
    return $matches;
}

顺便说一句,正则表达式比这慢得多(通常是10倍以上)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM