【问题标题】:recursively get user input value in array values递归获取数组值中的用户输入值
【发布时间】:2018-10-04 04:45:40
【问题描述】:

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

例如我有这个数组:

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

如果有人能提供帮助,我将不胜感激。感谢您的帮助。

【问题讨论】:

  • 您的用户界面是浏览器(参见 HTML 表单)还是控制台(参见 CLI 或 tty)?

标签: php arrays recursion php-7


【解决方案1】:

这是一个递归函数,可以做你想做的事。它遍历数组,寻找与字符串开头匹配的单词。它找到一个,然后递归地尝试在数组中查找与删除第一个匹配项后的字符串匹配的单词(不包括已匹配的单词)。

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

我做了一个稍微复杂一点的例子(demo on 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

更新

更新了基于 OPs cmets 的代码和演示,关于不需要匹配整个字符串。

【讨论】:

  • 很高兴。这是一个非常有趣的问题。
  • 顺便说一下,如果只从数组中获取 1 个值,它会返回错误。
  • 你的意思是如果数组中只有一个值吗?
  • @IhsanDn 问题是你的问题只显示了一个单词完全匹配字符串的例子,所以这就是我编码的。我会看一下,但请尝试将所有信息放在问题的开头。
  • @IhsanDn 查看我修改后的代码。希望这会做你想要的。
猜你喜欢
  • 2020-07-20
  • 1970-01-01
  • 2019-02-23
  • 2015-03-13
  • 2013-10-31
  • 2018-10-04
  • 2021-07-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多