Thursday, April 9, 2009

Split a string to an array by an array of positions

<?php
/**
* Split a string to an array by an array of positions.
* @param
* @return
$pos = array(0, 1, 3, 6, 10);
$str = "abbcccddddeeeee";
$arr = split_str_by_pos($str, $pos);
*/
function split_str_by_pos($str, $pos) {
$arr = array();

$count = count($pos);
$leng = strlen($str);

for ($i=0;$i<$count;$i++) {
$start = $pos[$i];
$end = ($i == $count - 1) ? $leng : $pos[$i+1];

$fieldVal = '';

for ($j = $start; $j < $end; $j++) {
$fieldVal .= $str[$j];
}

$arr[] = $fieldVal;
}

return $arr;
}
?>

No comments: