my split for php

來源:互聯網
上載者:User

 

代碼

<?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 ) 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.