preg_split

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

preg_split -- 用正則表達式分割字串

說明

array preg_split ( string pattern, string subject [, int limit [, int flags]] )

返回一個陣列,包括 subject 中沿著與 pattern 符合的邊界所分割的子串。

若果指定了 limit,則最多返回 limit 個子串,若果 limit 是 -1,則意味著沒有限制,可以用來繼續指定可選參數 flags

flags 可以是下列旗標的任意組合(用按位或運算符 | 組合):

PREG_SPLIT_NO_EMPTY

若果設定了本旗標,則 preg_split() 只返回非空的成分。

PREG_SPLIT_DELIM_CAPTURE

若果設定了本旗標,定界符模式中的括號表達式也會被捕捉並返回。本旗標增加於 PHP 4.0.5。

PREG_SPLIT_OFFSET_CAPTURE

若果設定了本旗標,若果設定本旗標,對每個出現的符合結果也同時返回其附屬的字串偏移量。注意這改變了返回的陣列的值,使其中的每個單元也是一個陣列,其中第一項為符合字串,第二項為其在 subject 中的偏移量。本旗標自 PHP 4.3.0 起可用。

例子 1. preg_split() 例子

<?php
// split the phrase by any number of commas or space characters,
// which include " ", \r, \t, \n and \f
$keywords preg_split ("/[\s,]+/""hypertext language, programming");
?>

例子 2. 將字串分割成字元

<?php
$str 
'string';
$chars preg_split('//'$str, -1PREG_SPLIT_NO_EMPTY);
print_r($chars);
?>

例子 3. 將字串分割為符合項及其偏移量

<?php
$str 
'hypertext language programming';
$chars preg_split('/ /'$str, -1PREG_SPLIT_OFFSET_CAPTURE);
print_r($chars);
?>

本例將輸出:

Array
(
    [0] => Array
        (
            [0] => hypertext
            [1] => 0
        )

    [1] => Array
        (
            [0] => language
            [1] => 10
        )

    [2] => Array
        (
            [0] => programming
            [1] => 19
        )

)

注: flags 是 PHP 4 Beta 3 增加的。

參見 spliti()split()implode()preg_match()preg_match_all()preg_replace()