12.13.2010

Explode a string with no delimiter in PHP

I needed a way to split a string by the character and put the results in an array.  Sounds like the perfect job for the explode function right?  Well, according to the manual:

If delimiter is an empty string (""), explode() will return FALSE


That's a bummer.  


UPDATE: I also tried str_split('whatever') but that has some problems with foreign strings.


But we can do something like this:


$str = "Let's split this string!";
// get the string length so we aren't paying for this in the loop
$strLen = strlen( $str );
      
// basically an "explode" on the string without needing delimiters
for ( $i = 0; $i < $strLen; $i++ )
{
    $arr[] = $str{$i};
}


print_r( $arr );

Enjoy!  Let me know what other ways you can come up with to do something similar.

4 comments:

Jani said...

How about the builtin function str_split, which does the job like so: str_split('whatever')

Rich Zygler said...

Its funny, that's what I started with, but I ran into problems with some foreign characters not working correctly. I'm not sure exactly why.

Jani said...

It probably doesn't handle UTF8 properly like many other PHP's string functions. It might be doable better using mb_split and /./ as the regex (any character).

Rich Zygler said...

Right, I know the PHP devs were adding UTF8 functionality to all the string functions without having to resort to the mb_ functions, but I'm not sure when that will be available.

Post a Comment