繁体   English   中英

递归获取数组值中的用户输入值

[英]recursively get user input value in array values

我倾向于递归,我想创建一个依赖于用户值的搜索引擎,并从数组中获取所有值,这些值共同构成用户键入的单词。

例如我有这个数组:

$array = array('it', 'pro', 'gram', 'grammer', 'mer', 'programmer');
$string = "itprogrammer";    

如果有人可以提供帮助,我会非常感激。 谢谢您的帮助。

这是一个递归函数,它将执行您想要的操作。 它遍历数组,寻找与字符串开头匹配的单词。 它找到一个,然后递归尝试在数组中找到单词(不包括已匹配的单词),该单词在删除了第一个匹配项之后与字符串匹配。

function find_words($string, $array) {
    // if the string is empty, we're done
    if (strlen($string) == 0) return array();
    $output = array();
    for ($i = 0; $i < count($array); $i++) {
        // does this word match the start of the string?
        if (stripos($string, $array[$i]) === 0) {
            $match_len = strlen($array[$i]);
            $this_match = array($array[$i]);
            // see if we can match the rest of the string with other words in the array
            $rest_of_array = array_merge($i == 0 ? array() : array_slice($array, 0, $i), array_slice($array, $i+1));
            if (count($matches = find_words(substr($string, $match_len), $rest_of_array))) {
                // yes, found a match, return it
                foreach ($matches as $match) {
                    $output[] = array_merge($this_match, $match);
                }
            }
            else {
                // was end of string or didn't match anything more, just return the current match
                $output[] = $this_match;
            }
        }
    }
    // any matches? if so, return them, otherwise return false
    return $output;
}

您可以使用所需的格式显示输出:

$wordstrings = array();
if (($words_array = find_words($string, $array)) !== false) {
    foreach ($words_array as $words) {
        $wordstrings[] = implode(', ', $words);
    }
    echo implode("<br>\n", $wordstrings);
}
else {
    echo "No match found!";
}

我做了一个稍微复杂的示例( rextester上的演示 ):

$array = array('pro', 'gram', 'merit', 'mer', 'program', 'it', 'programmer'); 
$strings = array("programmerit", "probdjsabdjsab", "programabdjsab");

输出:

string: 'programmerit' matches:

pro, gram, merit<br>
pro, gram, mer, it<br>
program, merit<br>
program, mer, it<br>
programmer, it

string: 'probdjsabdjsab' matches:

pro

string: 'programabdjsab' matches:

pro, gram<br>
program

更新

基于OP注释的有关不需要匹配整个字符串的更新的代码和演示。

暂无
暂无

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

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