简体   繁体   English

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

[英]FInd array of words in String using regex

I am looking to search some words in string , below is my code 我正在寻找字符串中的一些单词,下面是我的代码

$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;
}

This function return true or false , if word found it return 1 and if not it return 0.I need to return word which i am searching ,because i want to do another search on this word in mysql. 该函数返回true或false,如果找到的单词返回1,否则返回0。我需要返回正在搜索的单词,因为我想在mysql中对该单词进行另一个搜索。 Like if function found "Ary digital" then it should return "ary digital found". 就像功能找到“ Ary digital”一样,它应该返回“ ary digital found”。 Help required.Thanks. 需要帮助。谢谢。

You probably want to do something like this (untested): 您可能想做这样的事情(未经测试):

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

Then print_r($matches) to see the output of the matches array and grab the bit you want. 然后,print_r($ matches)查看matchs数组的输出并获取您想要的位。 From there you can return true/false etc. 从那里您可以返回true / false等。

Just rewrite what you already have. 只需重写您已有​​的内容即可。 Instead of returning a boolean push the matching keywords to a new array and return that one. 而不是返回布尔值,而是将匹配的关键字推送到一个新数组,然后返回该数组。

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;
}

By the way regexes are a lot slower (usually factor 10+) than this. 顺便说一句,正则表达式比这慢得多(通常是10倍以上)。

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

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