代碼
<?php
/*
*一、按指定符號分割字串,返回分割後的元素個數, 方法很簡單, 就是看字串中存在多少個分隔字元號,然後再加一,就是要求的結果。
*$str:要分割的字串
*$split:分隔字元號
*/
function Get_StrArrayLength($str,$split)
{
$location='';//當前位置
$start=''; //搜尋的開始位置
$length =1; //記錄數組長度
$str=trim($str);//去除空格
$location=strpos($str,$split);
while($location)
{
$start=$location+1;
$location=strpos($str,$split,$start);
$length=$length+1;
}
return $length;
}
/*
*二、按指定符號分割字串,返回分割後指定索引的第幾個元素,象數組一樣方便
*$str:要分割的字串
*$split:分隔字元號
*$index:取第幾個元素
*/
function Get_StrArrayStrOfIndex($str,$split,$index )
{
$location=0;//當前位置
$start=0; //搜尋的開始位置
$next =1; //下一個位置
$seed=strlen($index); //種子(分割字串的長度)
$str=trim($str);//去除空格
$location=strpos($str,$split);
while($location!=false&&$index>$next)
{
$start=$location+$seed;
$location=strpos($str,$split,$start);
$next=$next+1;
}
if($location==0)
{
$location=strlen($str)+1;
}
/*
* 這兒存在兩種情況:1、字串不存在分隔字元號 2、字串中存在分隔字元號,跳出while迴圈後,$location為0,那預設為字串後邊有一個分隔字元號。
*/
return substr($str,$start,$location-$start);
}
/*
*三、結合上邊兩個函數,象數組一樣遍曆字串中的元素,當然了,這裡就直接把它存到數組中
*$str:要分割的字串
*$split:分隔字元號
*/
function mySplit($str,$split)
{
$next=1;
$arr=array();
while($next<=Get_StrArrayLength($str,$split))
{
array_push($arr,Get_StrArrayStrOfIndex($str,$split,$next));
$next=$next+1;
}
return $arr;
}
/*
* 測試如下:
* */
$str='123|456|789';
$split='|';
$arr=mySplit($str,$split);
//輸出數組結構:
print_r($arr);
?>
輸出結果:
Array ( [0] => 123 [1] => 456 [2] => 789 )