Php 从字符串中提取特定组合的有效方法
所以我有这样一句话:Php 从字符串中提取特定组合的有效方法,php,combinations,Php,Combinations,所以我有这样一句话: one_two_three_four 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
one_two_three_four
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
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_3
,1_2
,1
现在,您需要一个辅助函数来使用新位置调用visitArray
这意味着,如果我们有这个数组[1,2,3]
我们需要调用visitArray[1,2,3]
,[2,3]
,[3]
因此,我们使用simple for循环定义了一个函数来循环数组值,每次调用visitArray()时,我们都会使用带有position
变量的array\u slice忽略一次调用
function callVisit($array, &$result, $position = 0) {
for($i = 0; $i < count($array); $i++)
visitArray(array_slice($array, $position++, count($array) - 1), $result);
}
因此,您需要通过传递两个参数来调用callVisit(),即数组、结果数组(应该存储结果的位置)
完整代码:
<?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>";
OP为什么要尝试这个?一个好的答案总是会有一个解释,说明做了什么以及为什么这样做,不仅是为了OP,而且是为了SO的未来访客。@JayBlanchard你是对的。但根据他缺少的需求,我的答案似乎仍然不正确。据我所知,他没有缺少的需求。似乎我们谈论的是从1到(N-1)
的范围,而不是1到N
的范围。看起来是这样的,但再看看他想要的结果。你看到了吗?