Search code examples
phparraysstringsplit

Populate array of individual letters from a string containing space-separated words


I have a string in php like this one:

$string = "Count the character frequency of this string";

When I used explode function the output display as:

Array ( 
    [0] => Count 
    [1] => the 
    [2] => character 
    [3] => frequency 
    [4] => of 
    [5] => this 
    [6] => string 
) 

But the output above doesn't satisfied me because I want to achieve an output which looks like this:

Array ( 
    [0] => C 
    [1] => o 
    [2] => u 
    [3] => n 
    [4] => t 
    [5] => t 
    [6] => h 
    [7] => e 
    [8] => c 
    [9] => h 
    [10] => a 
    [11] => r 
    [12] => a 
    [13] => c
    ...
)

I want to split into separate letters and omit the spaces.


Solution

  • Use str_split() after using str_replace() to get rid of the space characters:

     print_r(str_split(str_replace(' ', '', $string)));
    

    Demo

    If your string will contain other non alphanumeric characters you can use a regex to replace all non-alphanumeric characters:

    print_r(str_split(preg_replace('/[^\da-z]/i', '', $string)));
    

    Demo