简体   繁体   中英

Get all possible substring in php

I am trying to get a list of all substring of input. for input=a, substrings {'','a'} for input=ab, substrings {'','a','b','ab','ba'} for input=abc, substrings {'','a','b','c','ab','bc','ca','ba','cb','ac','abc','acb','bac','bca','cab','cba'} and so on.

The code I tried is here

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);

    }

and i have o/p of this code as below

在此处输入图片说明

在此处输入图片说明

Please suggest me what changes I need or any alternative idea to do this work.

function find_posible_substr($input){
    $input_len = strlen($input);
    $possubstr = array();
    $i = 0;
    while($i < $input_len){
        $j = 0;
        while($j < $input_len){
            $possubstr[] = substr($input, $j, $i + 1);
            if(substr($input, $j, $i + 1) == $input){
                break;
            }
            $j++;
        }
        $i++;
    }
    return $possubstr;
}

I don't know if you are still on this problem. But I want to share mine anyway. If the input is abc then the output will be as below.

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => ab
    [4] => bc
    [5] => c
    [6] => abc
)
<?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.

see this SO answer

$str = "abcd"; $str_arr = str_split($str);

for($i = 0; $i <= count($str_arr)-1 ;$i++){

for($j = $i+1 ; $j <= count($str_arr) ; $j++){

  for($k = $i; $k <= $j-1; $k++){
        $subsrt1.= $str_arr[$k];
  }
  $substr[] = $subsrt1;
  $subsrt1 = '';

}

} print_r($substr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM