PHP函數preg_split的正確使用方法_PHP教程

來源:互聯網
上載者:User
對於初學者來說,大家對說明 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 起可用。

提示

如果不需要Regex的功能,可以選擇使用更快(也更簡單)的替代函數如 explode() 或 str_split()。

例 1672. PHP函數preg_split例子:取得搜尋字串的成分

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

例 1673.PHP函數preg_split 將字串分割成字元

 
  1. $str = 'string';
  2. $chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
  3. print_r($chars);
  4. ?>

例 1674. PHP函數preg_split將字串分割為匹配項及其位移量

 
  1. $str = 'string';
  2. $chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
  3. print_r($chars);
  4. ?>

PHP函數preg_split例子將輸出:

 
  1. Array( [0] =>
  2. Array ( [0] => hypertext [1] => 0 ) [1] =>
  3. Array ( [0] => language [1] => 10 ) [2] =>
  4. Array ( [0] => programming [1] => 19 ))


http://www.bkjia.com/PHPjc/446302.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/446302.htmlTechArticle對於初學者來說,大家對 說明 array preg_split ( string $pattern, string $subject [, int $limit [, int $flags]] ) 返回一個數組,包含 subject 中沿著與 patter...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.