1. 程式人生 > >PHP 字串分割 explode 與 str_split 函式

PHP 字串分割 explode 與 str_split 函式

PHP 字串分割

用於分割字串。

相關函式如下:

·        explode():使用一個字串分割另一個字串

explode()

本函式為 implode() 的反函式,使用一個字串分割另一個字串,返回一個數組。

語法:

arrayexplode( string separator, string string [, int limit] )

引數說明:

引數

說明

separator

分割標誌

string

需要分割的字串

limit

可選,表示返回的陣列包含最多 limit 個元素,而最後那個元素將包含 string 的剩餘部分,支援負數。

例子:

<?php

$str= 'one|two|three|four';

print_r(explode('|',$str));

print_r(explode('|',$str, 2));

//負數的 limit(自 PHP 5.1 起)

print_r(explode('|',$str, -1));

?>

輸出結果如下:

Array

(

    [0] => one

    [1] => two

    [2] => three

    [3] => four

)

Array

(

    [0] => one

    [1] => two|three|four

)

Array

(

    [0] => one

    [1] => two

    [2] => three

)

str_split()

str_split() 將字串分割為一個數組,成功返回一個數組。

語法:

arraystr_split( string string [, int length] )

引數說明:

引數

說明

string

需要分割的字串

length

可選,表示每個分割單位的長度,不可小於1

例子:

<?php

$str= 'one two three';

$arr1= str_split($str);

$arr2= str_split($str, 3);

print_r($arr1);

print_r($arr2);

?>

輸出結果如下:

Array

(

    [0] => o

    [1] => n

    [2] => e

    [3] => 

    [4] => t

    [5] => w

    [6] => o

    [7] => 

    [8] => t

    [9] => h

    [10] => r

    [11] => e

    [12] => e

)

Array

(

    [0] => one

    [1] => tw

    [2] => o t

    [3] => hre

    [4] => e

)