分隔字符串,使用“str_split”就可以了好处是连空格也会作为数组的元素。我之前的例子就是因为前一个字符串包含2个空格,而后一个只有一个。但是输出的时候看到的显示都是一样的。
也可以按照其他分隔符进行分割,如“explode”或者“preg_split”,
php教程 explode() 函数
php string 函数
定义和用法
explode() 函数把字符串分割为数组。
语法
explode(separator,string,limit)参数 描述
separator 必需。规定在哪里分割字符串。
string 必需。要分割的字符串。
limit 可选。规定所返回的数组元素的最大数目。
例子
在本例中,我们将把字符串分割为数组:
<?php $str = "hello world. it's a beautiful day."; print_r (explode(" ",$str)); ?>
输出:
array ( [0] => hello [1] => world. [2] => it's [3] => a [4] => beautiful [5] => day. )
str_split 拆分函数
定义和用法
str_split() 函数把字符串分割到数组中。
语法
str_split(string,length)参数 描述
string 必需。规定要分割的字符串。
length 可选。规定每个数组元素的长度。默认是 1。
说明
如果 length 小于 1,str_split() 函数将返回 false。
如果 length 大于字符串的长度,整个字符串将作为数组的唯一元素返回。
例子
例子 1
输出:
array ( [0] => h [1] => e [2] => l [3] => l [4] => o )
例子 2
<?php print_r(str_split("hello",3)); ?>
输出:
Array ( [0] => hel [1] => lo )
preg_split -- 用正则表达式分割字符串
说明
array preg_split ( string pattern, string subject [, int limit [, int flags]])
返回一个数组,包含 subject 中沿着与 pattern 匹配的边界所分割的子串。
如果指定了 limit,则最多返回 limit 个子串,如果 limit 是 -1,则意味着没有限制,可以用来继续指定可选参数 flags。
flags 可以是下列标记的任意组合(用按位或运算符 | 组合):
preg_split_no_empty
如果设定了本标记,则 preg_split() 只返回非空的成分。
以上是一篇我在网上找到的关于拆分的字符串的文章 ,也是比较全的。今天我在我在做项目的时候,遇到了这样的一个问题,拆分中英文混合的字符串 。因为中文占有2个字节,当使用str_split函数时,悲剧的出现了乱码 。so,在网上找到了一个能够正确拆分字符串的函数 。此函是只支持 gb2312编码 ,其它的编码的字符串需要先转换编码 。
function arr_split_zh($tempaddtext){ $tempaddtext = iconv("UTF-8", "gb2312", $tempaddtext); $cind = 0; $arr_cont=array(); for($i=0;$i<strlen($tempaddtext);$i++) { if(strlen(substr($tempaddtext,$cind,1)) > 0){ if(ord(substr($tempaddtext,$cind,1)) < 0xA1 ){ //如果为英文则取1个字节 array_push($arr_cont,substr($tempaddtext,$cind,1)); $cind++; }else{ array_push($arr_cont,substr($tempaddtext,$cind,2)); $cind+=2; } } } foreach ($arr_cont as &$row) { $row=iconv("gb2312","UTF-8",$row); } return $arr_cont; }