Using PHP To Split A String Into Characters

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 variable.

$str = 'wibble';

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

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

This will print out the following:

 [0] => w
 [1] => i
 [2] => b
 [3] => b
 [4] => l
 [5] => e


Add new comment

The content of this field is kept private and will not be shown publicly.
17 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.