首页 > 语言 > PHP > 正文

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

2024-09-04 11:48:22
字体:大 中 小
来源:转载
供稿:网友

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() 只返回非空的成分,看个实例:

  1. <?php 
  2. $word_count = $word_length = 0; 
  3.  
  4. if ($fh = fopen('novel.txt','r')) { 
  5.   while (! feof($fh)) { 
  6.     if ($s = fgets($fh)) { 
  7.       $words = preg_split('/s+/',$s,-1,PREG_SPLIT_NO_EMPTY); 
  8.       foreach ($words as $word) { 
  9.         $word_count++; 
  10.         $word_length += strlen($word); 
  11.       } 
  12.     } 
  13.   } 
  14. } 
  15.  
  16. print sprintf("The average word length over %d words is %.02f characters.", 
  17.               $word_count, 
  18.               $word_length/$word_count); 
  19. ?> 

PHP简单应用:

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

由于分割后变成了数组,所以我们要利用foreach 来遍历输出了:

  1. <?php 
  2.    $delimitedText = "+A+++G+++++++++++C"; 
  3.    $fields = preg_split("/+{1,}/", $delimitedText); 
  4.     foreach($fields as $field) echo $field."<br />"; 
  5. ?> 
  6.  
  7. <? 
  8. $text = "a, o, p"; 
  9. $fruitarray = preg_split( "/, | and /", $text ); 
  10. print "<pre>n"; 
  11. print_r( $fruitarray ); 
  12. print "</pre>n"; 
  13. ?> 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表