0

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.

3
  • A few examples here.......... Commented Mar 27, 2015 at 1:28
  • This question is similar to: PHP: Split string into array, like explode with no delimiter. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Jul 22, 2024 at 10:22
  • This question is different from that question because the spaces must be omitted from the result. See my answer which implements a single call to achieve the result which would be inappropriate on the other page. A close vote with that page is not appropriate in my opinion. Commented Jul 22, 2024 at 10:25

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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',
)

Comments

-1

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

echo $string[0]

OUTPUTS

C

1 Comment

This does not answer the asked question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.