在这里,我有字符串......
$string = "Modern Country Kitchen";
我希望将 Word by Word 与 min 2 word 分开,我想要这样的结果...
$string1 = "Modern Country";
$string2 = "Country Kitchen";
$string3 = "Modern Kitchen";
如何制作逻辑代码,我应该使用什么PHP功能......?
到目前为止,我的逻辑只是使用explode()函数来爆炸字符串..
答案 0 :(得分:0)
所以,让我们从检索数组的每个组合/排列开始:
function getAllCombinations(array $input)
{
if (count($input) > 0)
{
foreach (getAllCombinations(array_slice($input, 1)) as $combination)
{
foreach (array_keys($input) as $index) {
yield array_merge(
array_slice($combination, 0, $index),
[$input[0]],
array_slice($combination, $index)
);
}
}
}
else
{
yield $input;
}
}
在这里看到它的工作:
php > foreach (getAllCombinations2([1, 2]) as $combination) {
php { var_dump($combination);
php { }
array(2) {
[0]=>
int(1)
[1]=>
int(2)
}
array(2) {
[0]=>
int(2)
[1]=>
int(1)
}
php >
现在我们需要将输入字符串转换为数组(您关于explode()
的权利!):
$string = "Modern Country Kitchen";
$words = explode(" ", $string);
现在看起来像这样:
php > var_dump($words);
array(3) {
[0]=>
string(6) "Modern"
[1]=>
string(7) "Country"
[2]=>
string(7) "Kitchen"
}
所以,现在我们可以得到这三个词的所有组合的数组:
$wordCombinations = iterator_to_array(getAllCombinations($words));
看到:
php > var_dump(iterator_to_array(getAllCombinations2($words)));
array(6) {
[0]=>
array(3) {
[0]=>
string(6) "Modern"
[1]=>
string(7) "Country"
[2]=>
string(7) "Kitchen"
}
...
现在,让我们将组合转换回字符串:
$combinations = array_map(function ($words) {
return implode(" ", $words);
}, $wordCombinations);
现在让我们来看看我们的最终结果:
php > var_dump($combinations);
array(6) {
[0]=>
string(22) "Modern Country Kitchen"
[1]=>
string(22) "Country Modern Kitchen"
[2]=>
string(22) "Country Kitchen Modern"
[3]=>
string(22) "Modern Kitchen Country"
[4]=>
string(22) "Kitchen Modern Country"
[5]=>
string(22) "Kitchen Country Modern"
}
php > var_dump($combinations[0]);
string(22) "Modern Country Kitchen"