简体   繁体   中英

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. Like if function found "Ary digital" then it should return "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. From there you can return true/false etc.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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