Using PHP To Split A String Into Characters

2nd September 2008

Use the following code to split a string into an array of characters.

$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);

It uses the preg_split() PHP function which takes a number of parameters. These area as follows:

  1. The regular expression to be used. In this case it matches everything.
  2. The string to be used in the regular expression.
  3. This is the character limit. In this case -1 mean no limit, so the function will work for any size of string.
  4. The last parameter can be a flag or series of flags separated by the | character. In this case the PREG_SPLIT_NO_EMPTY flag is used. This prevents the function from returning any empty strings. So if your string has any spaces in it they will not be returned.

To give an example, take the following string varaible.

$str = 'wibble';

This can be passed into the code and printed out like this.

  1. $chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
  2. echo ''.print_r($chars,true).'';

This will print out the following:

  1. Array
  2. (
  3. [0] => w
  4. [1] => i
  5. [2] => b
  6. [3] => b
  7. [4] => l
  8. [5] => e
  9. )

Add new comment

The content of this field is kept private and will not be shown publicly.