开发者

PHP in_array Find Any Matches

I am开发者_如何学Go trying to figure out how to match any words within an array. For example, the code bellow works for finding "Test Name" within an array but does not find "Another Test Name" (due to the word "Another") within the array. Any ideas?

if (in_array($html[$i], $eventsarray))
{
    $topeventaa = "yes";
}
else
{
    $topeventaa = "no";
}


Taken from http://php.net/manual/en/function.in-array.php

<?php

/**
 * Takes a needle and haystack (just like in_array()) and does a wildcard search on it's values.
 *
 * @param    string        $string        Needle to find
 * @param    array        $array        Haystack to look through
 * @result    array                    Returns the elements that the $string was found in
 */
function find ($string, $array = array ())
{       
    foreach ($array as $key => $value) {
        unset ($array[$key]);
        if (strpos($value, $string) !== false) {
            $array[$key] = $value;
        }
    }       
    return $array;
}

?>


If you want to match any of the words to those in your array, you may want to use explode on your string and then check each token as you do in your example.


We probably need more information, but you can create variable with the pattern matching you need with preg_match and pass it as the argument in your search.

preg_replace and str_replace may be helpful, depending on what exactly you're trying to accomplish.


You may want to look into recursive function calls, like when traversing through all the directories within a directory tree. I'd splice the array up to the index where it was found, leaving the remainder to be passed back into the same function to search through again. Depending on what results you want from knowing the number of occurrences of words within a string could we then start to break down the problem and write some code.


Justin, there's no direct way--no existing built-in function--to do what I believe you seek; you must iterate over the array yourself, along the lines of

$topeventaa = "no";
for ($eventsarray as $key=>$value){
    if (0 <= strpos($html[$i], $eventsarray[$key])) {
        $topeventaa = "yes";
        break;
    }
}


Use preg_grep instead of in_array to find all elements of an array matching a given pattern.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜