explode() 函數(shù)把字符串分割為數(shù)組;
implode() 函數(shù)把數(shù)組元素組合為一個(gè)字符串。
explode
定義 array explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] )
參數(shù): limit 限制結(jié)果的個(gè)數(shù)。
$str = "hi, jason, world"; print_r(explode(',', $str)); print_r(explode(',', $str, 2));
結(jié)果:
Array ( [0] => hi [1] => jason [2] => world ) Array ( [0] => hi [1] => jason, world )
練習(xí)題例子:定義一個(gè)字符串a(chǎn),計(jì)算出下劃線后面的值相加得多少,使用分割字符串函數(shù)。
$a='331612_1,331495_1,331461_2,331559_1,333080_1,333555_1,331448_1,331618_1,333388_1,33 3408_1,327937_1,331615_1,331499_1'; $arr=explode(',',$a); $sum=0; foreach ($arr as $value) { $ary=explode('_', $value); $sum+=$ary[1]; } print_r($sum);
implode
定義 string implode ( string $glue , array $pieces )
<?php $array = array( 'lastname' , 'email' , 'phone' ); $comma_separated = implode ( "," , $array ); echo $comma_separated ; // lastname,email,phone