获取所有可能的子串在PHP

获取所有可能的子串在PHP

问题描述:

我试图让输入的所有字符串列表。 输入= A,子串{ '', '一个'} 输入= AB,子串{ '', 'A', 'B', 'AB', 'BA'} 输入= ABC,子串{ '', 'A', 'b', 'C', 'AB', 'BC', 'CA', 'BA', 'CB', 'AC', 'ABC', 'ACB', 'BAC' 'BCA', '出租车', 'CBA'} 等。获取所有可能的子串在PHP

我尝试的代码是在这里

function get_substr($string){ 
     $array=str_split($string); 
     static $k=0; 
     for ($i=0; $i <count($array) ; $i++) { 
      for ($j=0; $j <count($array) ; $j++) { 
       $new_array[$k]=substr($string, $i, $j - $i + 1); 
       $k++; 

      } 
     } 
     return($new_array); 

    } 

和我有这个代码的O/P如下

enter image description here

enter image description here

请建议我什么样的变化,我需要或任何其他想法来做这项工作。

+0

置换是解决 –

+1

您需要的输出是*不*子。 'ba'不是'abc'的子字符串。 – Eiko

+0

对不起@Eiko。如果您对我的问题有任何想法,请。 –

<?php 
// function to generate and print all N! permutations of $str. (N = strlen($str)). 
function permute($str,$i = null,$n = null) { 
    if(is_null($n)) $n = mb_strlen($str); 
    if(is_null($i)) $i = 0; 
    if ($i == $n) 
     print "$str \n"; 
    else { 
     for ($j = $i; $j < $n; $j++) { 
      swap($str,$i,$j); 
      permute($str, $i+1, $n); 
      swap($str,$i,$j); // backtrack. 
     } 
    } 
} 
// function to swap the char at pos $i and $j of $str. 
function swap(&$str,$i,$j) { 
    $temp = $str[$i]; 
    $str[$i] = $str[$j]; 
    $str[$j] = $temp; 
} 

$str = "hey"; 
permute($str); // call the function. 

看到这个SO answer

+0

如果你不满意,请说明原因! – Iceman

+0

您可以从参数中删除'$ n'。这不是C :) – vfsoraki

+1

也许用'mb_strlen'只是为了编码问题是安全的。 – vfsoraki