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() 只返回非空的成分,看个实例:
- <?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);
- ?>
PHP简单应用:
- <?
- $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";
- ?>
(责任编辑:admin) |