php分割字符串并輸出數(shù)組字符例子

字號:


    在php中分割字符函數(shù)可以使用explode()函數(shù),但是使用此函數(shù)必須要有一個規(guī)律了,如以|分開或以其它字符分開,這樣我們就可以直接使用explode把字符串分成數(shù)組之后再利用for遍歷輸出,下面來看幾個例子。
    explode() 函數(shù)把字符串分割為數(shù)組。
    語法
    explode(separator,string,limit)
    例子一
    代碼如下:
    <?php
    $test='472347127,893372115,850965403';
    $r=explode(,,$test);
    for($i=0;$i<sizeof($r);$i++)
    { echo $i... $r[$i].; }
    ?>
    輸出: 0.472347127 1.893372115 2.850965403
    例子二
    代碼如下:
    <?php
    $a=893372115,472347127,850965403 ;
    $b=explode(,,$a);
    foreach($b as $bb)
    { echo $bb.; //print_r($b); }
    ?>
    輸出: 893372115 472347127 850965403 php
    逗號 分割字符串
    利用 explode 函數(shù)分割字符串到數(shù)組
    代碼如下:
    <?php
    $source = hello1,hello2,hello3,hello4,hello5;//按逗號分離字符串
    $hello = explode(',',$source);
    for($index=0;$index<count($hello);$index++){
    echo $hello[$index];echo </br>;
    }
    ?>
    split函數(shù)進(jìn)行字符分割
    代碼如下:
    <?php
    // 分隔符可以是斜線,點,或橫線
    $date = 04/30/1973;
    list($month, $day, $year) = split ('[/.-]', $date);
    echo month: $month; day: $day; year: $year<br />n;
    ?>