5.4.17PHP下explode分割字符串函数
Posted by 撒得一地 on 2016年4月4日 in PHP入门教程
字符串的分割是通过explode()函数实现的。explode()函数按照指定的规则对一个字符串进行分割,返回值为数组。
语法格式如下:
array explode(string separator,string str,[int limit])
explode()函数的参数说明如下所示:
separator:必要参数,指定的分隔符。如果separator为空字符串(“”),explode()将返回false。如果separator所包含的值在str中找不到,那么explode()函数将返回包含str单个元素的数组。 str:必要参数,指定将要被进行分割的字符串。 limit:可选参数,如果设置了limit参数,则返回的数组包含最大limit个元素,而最后的元素将包含string剩余部分;如果limit参数是负数,则返回除了最后-limit个元素外的所有元素。
实例:使用explode()函数实现字符串分割,代码如下:
<?php $str = "id1,id2,id3,id4,id5"; print_r(explode(",",$str)); print_r(explode(",",$str,3)); print_r(explode(",",$str,-2)); ?>
输出:
Array ( [0] => id1 [1] => id2 [2] => id3 [3] => id4 [4] => id5 ) Array ( [0] => id1 [1] => id2 [2] => id3,id4,id5 ) Array ( [0] => id1 [1] => id2 [2] => id3 )