Need string formation with space in php

筅森魡賤 提交于 2019-12-08 14:20:40

问题


$string='to kill a mocking bird';

Need output like below format

Output:

'"To kill a mocking bird", "Tokill a mocking bird", "Tokilla mocking bird", "Tokillamocking bird", "Tokillamockingbird", ,"To kill a mockingbird" ,"To kill amockingbird" ,"To killamockingbird"';

I used below Script

$array = is_string($arg) ? str_split($arg) : $arg;

if(1 === count($array))
  return $array;


  $result = array();
    foreach($array as $key => $item)
        foreach(permute(array_diff_key($array, array($key => $item))) as $p)
            $result[] = $item .' '. $p;
    return $result;

回答1:


I use explode to make it an array that I can loop through.
In the loop I use implode to add space and array_slice to select the corresponding words to join/add space between.
I loop once forward and once backwards to get all combinations.

$str='to kill a mocking bird';

$arr = explode(" ", $str);
Echo $str."\n";

For($i=1;$i<count($arr);$i++){
    Echo implode("", array_slice($arr, 0,$i)) . implode(" ", array_slice($arr, $i)) . "\n";
}

For($i=count($arr)-1;$i>1;$i--){
     Echo implode(" ", array_slice($arr, 0, $i)) . implode("", array_slice($arr,$i, count($arr))) . "\n";
}

https://3v4l.org/QVIKG



来源:https://stackoverflow.com/questions/47691979/need-string-formation-with-space-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!