从字符串中获取特定组合的有效方法

Efficient Way to specific combinations from string

所以我有这样一个短语:

one_two_three_four

.. 为了清楚起见,它也可以是这样的:

one_two_three_four_five_six_seven_eight_nine_ten_eleven_twelve

..但为了简洁起见,我将以这个为例:

one_two_three_four

根据字符串,我想创建以下关键字

one
one_two
one_two_three
two
two_three
two_three_four
three
three_four
four

我正在寻找最有效的方法(在 PHP 中)来解析这样的字符串(有些会更大)。

我能做到这一点:

$keyword = explode('_', $string);

所以现在我有一个这样的数组:

one
two
three
four

我对如何从原始字符串进入变体感到困惑。

首先你需要将字符串分解为 _

$str = 'one_two_three_four_five_six';
$array = explode('_', $str);

添加一个空数组来存储结果

$result = [];

定义一个递归函数接受一个数组,内爆数组值,删除最后一个元素并调用相同的数组直到长度为0

function visitArray($array, &$result) {
    if(count($array) == 0) //Check if length is 0 (Stop executing)
        return;
    $result[] = implode('_', $array); //Implode array values
    return visitArray(array_slice($array, 0, count($array) -  1), $result); //Remove last element and call again the same function
}

因此,如果您将 [1, 2, 3] 传递给 visitArray,您将拥有 结果数组中 1_2_31_21

现在你需要一个辅助函数来调用 visitArray 新位置,

也就是说,如果我们有这个数组[1, 2, 3]

我们需要调用 visitArray [1,2,3], [2,3], [3]

所以我们定义了一个带有简单 for 循环的函数来遍历数组值,每次我们调用 visitArray() 并且我们使用 [=64= 忽略调用一次] 与 position 变量。

function callVisit($array, &$result, $position = 0) {
    for($i = 0; $i < count($array); $i++)
        visitArray(array_slice($array, $position++, count($array) - 1), $result);
}

更新: 如果您需要删除位置参数,您可以将 forloop 替换为如下列表:

function callVisit($array, &$result) {
    while (list(,$v) = each($array)) 
    { 
        visitArray($array, $result);
        array_shift($array); //Remove first element
    } 
}

因此您需要通过传递两个参数来调用 callVisit(),数组,结果数组(应存储结果的位置)

callVisit($array, $result);

完整代码:

<?php

$str = 'one_two_three_four_five_six';

$array = explode('_', $str);

$result = [];


function callVisit($array, &$result, $position = 0) {
    for($i = 0; $i < count($array); $i++) 
        visitArray(array_slice($array, $position++, count($array) - 1), $result);
}

function visitArray($array, &$result) {
    if(count($array) == 0)
        return;
    $result[] = implode('_', $array);
    return visitArray(array_slice($array, 0, count($array) -  1), $result);
}


callVisit($array, $result);

echo "<pre>", json_encode($result, JSON_PRETTY_PRINT), "</pre>";