How to find all substrings of a string in PHP

前端 未结 9 1015
悲&欢浪女
悲&欢浪女 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:38

    And this question will not be complete without the recursive answer:

    function get_substrings($str){
        $len = strlen($str);
        $ans = array();
        $rest = array();
        for ($i = 1; $i <= $len; $i++) {                 
            $ans[] = substr($str, 0, $i);        
        }
        if($str){
            $rest = get_substrings(substr($str, 1));
        }
        return array_merge($ans, $rest);
    }
    
    $subs = get_substrings("abc");
    print_r($subs);
    

提交回复
热议问题