php preg_split()字串分割函數的使用方法

來源:互聯網
上載者:User

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

返回一個數組,包含 subject 中沿著與 pattern Regex來匹配的邊界所分割的子串。

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

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

PREG_SPLIT_NO_EMPTY
如果設定了本標記,則 preg_split() 只返回非空的成分

看個執行個體

<?php教程
$word_count = $word_length = 0;

if ($fh = fopen('novel.txt','r')) {
  while (! feof($fh)) {
    if ($s = fgets($fh)) {
      $words = preg_split('/s+/',$s,-1,PREG_SPLIT_NO_EMPTY);
      foreach ($words as $word) {
        $word_count++;
        $word_length += strlen($word);
      }
    }
  }
}

print sprintf("The average word length over %d words is %.02f characters.",
              $word_count,
              $word_length/$word_count);
?>

簡單應用

<?
$user_info = "+J+++G+++++w";
$fields = preg_split("/+{1,}/", $user_info);
while ($x < sizeof($fields)) :
   print $fields[$x]. "<br>";
   $x++;
endwhile;
?>

由於分割後變成了數組,所以我們要利用foreach 來遍曆輸出了。

<?php
   $delimitedText = "+A+++G+++++++++++C";
   $fields = preg_split("/+{1,}/", $delimitedText);
    foreach($fields as $field) echo $field."<br />";
?>

<?
$text = "a, o, p";
$fruitarray = preg_split( "/, | and /", $text );
print "<pre>n";
print_r( $fruitarray );
print "</pre>n";
?>
 

聯繫我們

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