How to find all substrings of a string in PHP

前端 未结 9 993
悲&欢浪女
悲&欢浪女 2020-12-11 06:05

I need to convert strings of the form

\"a b c\"

into arrays of the form

Array
(
    [0] => a
    [1] => a b
    [2] =         


        
相关标签:
9条回答
  • 2020-12-11 06:44
    <?php
    function get_all_substrings($input){
        $subs = array();
        $length = strlen($input);
        for($i=0; $i<$length; $i++){
            for($j=$i; $j<$length; $j++){
                $subs[] = substr($input, $i, $j);               
            }
        }
        return $subs;
    }
    
    $subs = get_all_substrings("Hello world!");
    print_r($subs);
    
    ?>
    

    Even if there's a fancy two-liner to accomplish this, I doubt it's any more efficient or easy to understand (for anybody to understand it they'd probably have to look at the docs. Most folks probably get what substr does without even looking it up).

    0 讨论(0)
  • 2020-12-11 06:50

    Substrings are not permutations. explode() the string, then use two nested loops along with array_slice() to get the relevant elements.

    0 讨论(0)
  • 2020-12-11 06:52

    All possible substrings

      <?php   
             $str1 = "ABCD";
             $len = strlen($str1);
             $arr = array();
             for($i = 0; $i < $len; $i++){  
                 for($j = 0; $j < $len - $i; $j++){  
                     $arr [] = substr($str1,$i,($j+1));  
                 }  
             }  
    
             echo(json_encode($arr));
         ?>
    
    0 讨论(0)
提交回复
热议问题