psuresh
psuresh

Reputation: 584

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

enter image description here

enter image description here

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

Upvotes: 0

Views: 1033

Answers (3)

Hiral Shah
Hiral Shah

Reputation: 1

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

Upvotes: 0

N.Kaewkhat
N.Kaewkhat

Reputation: 19

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
)

Upvotes: 1

Iceman
Iceman

Reputation: 6145

<?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

Upvotes: 0

Related Questions