【问题标题】:Split string into array of character strings and count of splitted charcters in php将字符串拆分为字符串数组和php中拆分字符的计数
【发布时间】:2013-02-09 14:33:47
【问题描述】:

我需要将一个字符串拆分为单个字符串数组并获取拆分字符的数量。

例如,拆分“字符”会得到数组"c", "h", "a", "r", "a", "c", "t", "e", "r"

编辑

是否可以使用内置函数计算拆分的字符串字符?

Array ( [c] => 2 [h] => 1 [a] => 2 [r] => 2 [t] => 1 [e] => 1 ) 

【问题讨论】:

    标签: php arrays string split


    【解决方案1】:

    [数组$array

    $array = str_split('Cat');
    


    str_split() 拆分后将如下所示:

    ARRAY
    {
       [0] = 'C'
       [1] = 'a'
       [2] = 't'
    }
    



    对已编辑问题的回答

    可以,可以使用count_chars()函数

    $str = "CHARACTERS";
    
    $array = array();
    
    foreach (count_chars($str, 1) as $i => $val) {
       array[] = array($str, $i);
    }
    

    将输出以下内容:

    ARRAY
    {
       [0] = ARRAY("C" => 2)
       [1] = ARRAY("H" => 1)
    }
    

    【讨论】:

    • +1 感谢您的回答。打印时$arrayArray ( [0] => Array ( [0] => CHARACTERS [1] => 65 ) [1] => Array ( [0] => CHARACTERS [1] => 67 )....等
    【解决方案2】:

    使用php函数str_split, 这里的例子:

    $array = str_split("cat");
    

    【讨论】:

      【解决方案3】:

      使用str_split

      $array = str_split("cat");
      

      试试count_chars:

      <?php
      $data = "Two Ts and one F.";
      
      foreach (count_chars($data, 1) as $i => $val) {
         echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n";
      }
      ?>
      

      上面的例子会输出:

      There were 4 instance(s) of " " in the string.
      There were 1 instance(s) of "." in the string.
      There were 1 instance(s) of "F" in the string.
      There were 2 instance(s) of "T" in the string.
      There were 1 instance(s) of "a" in the string.
      There were 1 instance(s) of "d" in the string.
      There were 1 instance(s) of "e" in the string.
      There were 2 instance(s) of "n" in the string.
      There were 2 instance(s) of "o" in the string.
      There were 1 instance(s) of "s" in the string.
      There were 1 instance(s) of "w" in the string.
      

      【讨论】:

        【解决方案4】:

        你需要使用str_split

        $array = str_split($str, 1);
        

        【讨论】:

          【解决方案5】:

          在这里使用爆炸doc

           /* A string that doesn't contain the delimiter will simply return a one-length array of the original string. */
           $input1 = "hello";
           $input2 = "hello,there";
           var_dump( explode( ',', $input1 ) );
           var_dump( explode( ',', $input2 ) );
          

          【讨论】:

          • 你的语法会给我Array ( [0] =&gt; cat )。我需要的是Array ( [0] =&gt; c [1] =&gt; a [2] =&gt; t )
          猜你喜欢
          • 2012-02-22
          • 2016-04-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-10
          • 1970-01-01
          相关资源
          最近更新 更多