Tech Tidbits - Ruby, Ruby On Rails, Merb, .Net, Javascript, jQuery, Ajax, CSS...and other random bits and pieces.

Thursday, July 5, 2007

Emulate PHP5 str_split() in PHP4

/* emulate the php5 str_split function
* array str_split( string $string [, int $split_length])
* Converts a string to an array
* If the optional split_length param is specified, the returned array
* will be broken down into chunks with each being split_length in
* length, otherwise each chuck will be one character in length.
* False is returned if split_length is less than 1. If the split_length
* length exceeds the length of string, the entire string is returned
* as the first (and only) array element.
*/

If you want to use optional split_length:

function str_split($str, $l=1) {
$str_array = explode("\r\n", chunk_split($str,$l));
return $str_array;
}


Or optionally, if you just need the simple split (split_length=1):

function str_split($str) {
$str_array=array();
$len=strlen($str);
for($i=0; $i<$len; $i++) {
$str_array[]=$str{$i};
}
return $str_array;
}

No comments:

About Me

My photo
Developer (Ruby on Rails, iOS), musician/composer, Buddhist, HSP, Vegan, Aspie.

Labels