Home > PHP Strings > Using PHP To Split A String Into Characters

Using PHP To Split A String Into Characters

September 2nd, 2008 Leave a comment Go to comments

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.

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

This will print out the following:

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

  1. August 15th, 2009 at 22:54 | #1

    Or you can just use str_split().

  1. No trackbacks yet.