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:
- The regular expression to be used. In this case it matches everything.
- The string to be used in the regular expression.
- This is the character limit. In this case -1 mean no limit, so the function will work for any size of string.
- 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:
-  => w
-  => i
-  => b
-  => b
-  => l
-  => e