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 @H_403_22@$word_count = $word_length = 0;
- @H_403_22@if ($fh = fopen('novel.txt','r')) {
- while (! feof($fh)) { @H_403_22@ if ($s = fgets($fh)) {
- $words = preg_split('/s+/',$s,-1,PREG_SPLIT_NO_EMPTY); @H_403_22@ foreach ($words as $word) {
- $word_count++; @H_403_22@ $word_length += strlen($word);
- } @H_403_22@ }
- } @H_403_22@}
- @H_403_22@print sprintf("The average word length over %d words is %.02f characters.",
- $word_count, @H_403_22@ $word_length/$word_count);
- ?>
PHP简单应用:
由于分割后变成了数组,所以我们要利用foreach 来遍历输出了:
- <?PHP @H_403_22@ $delimitedText = "+A+++G+++++++++++C";
- $fields = preg_split("/+{1, $delimitedText); @H_403_22@ foreach($fields as $field) echo $field."<br />";
- ?> @H_403_22@
- <? @H_403_22@$text = "a, o, p";
- $fruitarray = preg_split( "/, | and /", $text ); @H_403_22@print "<pre>n";
- print_r( $fruitarray ); @H_403_22@print "</pre>n";
- ?>