Lee Lee
Lee Lee

Reputation: 583

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.

Upvotes: 0

Views: 569

Answers (3)

mickmackusa
mickmackusa

Reputation: 47991

In one function call, split the string on zero or more spaces and omit any empty values.

Code: (Demo)

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

var_export(
    preg_split(
        '/ */',
        $string,
        0,
        PREG_SPLIT_NO_EMPTY
    )
);

Output:

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',
  14 => 't',
  15 => 'e',
  16 => 'r',
  17 => 'f',
  18 => 'r',
  19 => 'e',
  20 => 'q',
  21 => 'u',
  22 => 'e',
  23 => 'n',
  24 => 'c',
  25 => 'y',
  26 => 'o',
  27 => 'f',
  28 => 't',
  29 => 'h',
  30 => 'i',
  31 => 's',
  32 => 's',
  33 => 't',
  34 => 'r',
  35 => 'i',
  36 => 'n',
  37 => 'g',
)

Upvotes: 2

John Conde
John Conde

Reputation: 219874

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

Upvotes: 3

gwillie
gwillie

Reputation: 1899

You can access the string as a character array by default in php

echo $string[0]

OUTPUTS

C

Upvotes: -1

Related Questions