close


[php]str_split — 將字符串轉換為數組


官方範例
<?php


$str = "Hello Friend";


$arr1 = str_split($str);
$arr2 = str_split($str, 3);


print_r($arr1);
print_r($arr2);


?>
以上例程會輸出:
Array
(
    [0] => H
    [1] => e
    [2] => l
    [3] => l
    [4] => o
    [5] =>
    [6] => F
    [7] => r
    [8] => i
    [9] => e
    [10] => n
    [11] => d
)


Array
(
    [0] => Hel
    [1] => lo
    [2] => Fri
    [3] => end
)


其它範例
function str_rsplit($str, $sz)
{
    // splits a string "starting" at the end, so any left over (small chunk) is at the beginning of the array.    
    if ( !$sz ) { return false; }
    if ( $sz > 0 ) { return str_split($str,$sz); }    // normal split
    
    $l = strlen($str);
    $sz = min(-$sz,$l);
    $mod = $l % $sz;
    
    if ( !$mod ) { return str_split($str,$sz); }    // even/max-length split


    // split
    return array_merge(array(substr($str,0,$mod)), str_split(substr($str,$mod),$sz));
}


$str = 'aAbBcCdDeEfFg';
str_split($str,5); // return: {'aAbBc','CdDeE','fFg'}
str_rsplit($str,5); // return: {'aAbBc','CdDeE','fFg'}
str_rsplit($str,-5); // return: {'aAb','BcCdD','eEfFg'}




//給php4使用的範例

function str_split_php4( $text, $split = 1 ) {
    // place each character of the string into and array
    $array = array();
    for ( $i=0; $i < strlen( $text ); ){
        $key = NULL;
        for ( $j = 0; $j < $split; $j++, $i++ ) {
            $key .= $text[$i];
        }
        array_push( $array, $key );
    }
    return $array;
}

arrow
arrow
    全站熱搜

    stockwfj3 發表在 痞客邦 留言(0) 人氣()