explode() 函数把字符串分割为数组;
implode() 函数把数组元素组合为一个字符串。
explode
定义 array explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] )
参数: limit 限制结果的个数。
$str = "hi, jason, world"; print_r(explode(',', $str)); print_r(explode(',', $str, 2));
结果:
Array ( [0] => hi [1] => jason [2] => world ) Array ( [0] => hi [1] => jason, world )
练习题例子:定义一个字符串a,计算出下划线后面的值相加得多少,使用分割字符串函数。
$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