How to find all substrings of a string in PHP

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

    This works and it works also with multibyte strings, all the methods above don't, they return null and duplicated values.

    function substrings($str, $charset = 'UTF-8') {   
      $length = mb_strlen($str, $charset);
    
      $subs = [];
      for ($i = 0; $i < $length; $i++)
        for ($j = 1; $j <= $length; $j++)
          $subs[] = mb_substr($str, $i, $j, $charset);
    
      return array_unique($subs);
    }
    
    print_r(substrings("php"));
    

提交回复
热议问题