PHP explode()函数的几个应用和implode()函数有什么区别
explode()函数介绍
explode()函数可以把字符串分割为数组。
语法:explode(separator,string,limit)。
本函数返回由字符串组成的数组,其中的每个元素都是由separator作为边界点分割出来的子字符串。
separator参数不能是空字符串。如果separator为空字符串(""),explode()将返回FALSE。如果separator所包含的值在string中找不到,那么explode()将返回包含string中单个元素的数组。
如果设置了limit参数,则返回的数组包含最多limit个元素,而最后那个元素将包含string的剩余部分。
如果limit参数是负数,则返回除了最后的-limit个元素外的所有元素。此特性是PHP5.1.0中新增的。
ProgramList:explode()例子
<?php
//Example
$fruit="AppleBananaOrangeLemonMangoPear";
$fruitArray=explode("",$fruit);
echo$fruitArray[];//Apple
echo$fruitArray[];//Banana
//Example
$data="gonn:*:nowamagic:::/home/foo:/bin/sh";
list($user,$pass,$uid,$gid,$gecos,$home,$shell)=explode(":",$data);
echo$user;//gonn
echo$pass;//*
?>
程序运行结果:
Apple
Banana
gonn
*
ProgramList:使用limit参数的explode()例子
<?php
$str='one|two|three|four';
//positivelimit
print_r(explode('|',$str,));
//negativelimit(sincePHP.)
print_r(explode('|',$str,-));
?>
程序运行结果:
Array ( []=>one []=>two|three|four ) Array ( []=>one []=>two []=>three )
ProgramList:将字符串化为键值数组
<?php
//convertspurestringintoatrimmedkeyedarray
functionstringKeyedArray($string,$delimiter=',',$kv='=>'){
if($a=explode($delimiter,$string)){//createparts
foreach($aas$s){//eachpart
if($s){
if($pos=strpos($s,$kv)){//key/valuedelimiter
$ka[trim(substr($s,,$pos))]=trim(substr($s,$pos+strlen($kv)));
}else{//keydelimiternotfound
$ka[]=trim($s);
}
}
}
return$ka;
}
}//stringKeyedArray
$string='a=>,b=>,$a,c=>%,true,d=>abc';
print_r(stringKeyedArray($string));
?>
程序运行结果:
Array
(
[a]=>
[b]=>
[]=>$a
[c]=>%
[]=>true
[d]=>abc
)
PS:PHP函数implode()与explode()函数的不同之处
以上内容给大家介绍了explode()函数的具体用法。当我们遇到PHP函数implode()把数组元素组合为一个字符串。
implode(separator,array)
separator可选。规定数组元素之间放置的内容。默认是""(空字符串)。
array必需。要结合为字符串的数组。
虽然separator参数是可选的。但是为了向后兼容,推荐您使用使用两个参数。
PHP函数implode()的例子
<?php
$arr=array('Hello','World!','Beautiful','Day!');
echoimplode("",$arr);
?>
输出:
HelloWorld!BeautifulDay!
上面这段代码示例就是PHP函数implode()的具体实现功能的展现。