PHP 正则表达式分割 preg_split 与 split 函数
2012-03-12 13:33
633 查看
preg_split()
preg_ split() 函数用于正则表达式分割字符串。语法:
array preg_split( string pattern, string subject [, int limit [, int flags]] )
返回一个数组,包含 subject 中沿着与 pattern 匹配的边界所分割的子串。
参数 | 说明 |
---|---|
pattern | 正则表达式 |
subject | 需要匹配分割的对象 |
limit | 可选,如果指定了 limit ,则最多返回 limit 个子串,如果 limit 是 -1,则意味着没有限制,可以用来继续指定可选参数 flags |
flags | 设定 limit 为 -1 后可选,可以是下列标记的任意组合(用按位或运算符 | 组合): PREG_SPLIT_NO_EMPTY:preg_split() 只返回非空的成分 PREG_SPLIT_DELIM_CAPTURE:定界符模式中的括号表达式也会被捕获并返回 PREG_SPLIT_OFFSET_CAPTURE:对每个出现的匹配结果也同时返回其附属的字符串偏移量。注意这改变了返回的数组的值,使其中的每个单元也是一个数组,其中第一项为匹配字符串,第二项为其在 subject 中的偏移量。 |
<?php $str = "php mysql,apache ajax"; $keywords = preg_split("/[\s,]+/", $str); print_r($keywords); ?>
输出结果为:
Array ( [0] => php [1] => mysql [2] => apache [3] => ajax )
例子 2 :
<?php $str = 'string'; $chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY); print_r($chars); ?>
输出结果为:
( [0] => s [1] => t [2] => r [3] => i [4] => n [5] => g )
例子 3 :
<?php $str = "php mysql,apache ajax"; $keywords = preg_split("/[\s,]+/", $str, -1, PREG_SPLIT_OFFSET_CAPTURE); print_r($keywords); ?>
输出结果为:
Array ( [0] => Array ( [0] => php [1] => 0 ) [1] => Array ( [0] => mysql [1] => 4 ) [2] => Array ( [0] => apache [1] => 10 ) [3] => Array ( [0] => ajax [1] => 17 ) )
split()
split() 函数同 preg_split() 类似,用正则表达式将字符串分割到数组中,返回一个数组,但推荐使用 preg_split() 。语法:
array split( string pattern, string string [, int limit] )
如果设定了 limit ,则返回的数组最多包含 limit 个单元,而其中最后一个单元包含了 string 中剩余的所有部分。如果出错,则返回 FALSE。
例子:
<?php $date = "2008-08-08 20:00:01"; print_r( split('[- :]', $date) ); ?>
输出结果:
Array ( [0] => 2008 [1] => 08 [2] => 08 [3] => 20 [4] => 00 [5] => 01 )
提示
如果不需要正则表达式的功能,可以选择使用更快(也更简单)的替代函数如explode() 或
str_split() 。
split() 函数对大小写敏感,如果在匹配字母字符时忽略大小写的区别,请使用用法相同的 spliti() 函数
相关文章推荐
- PHP 正则表达式分割 preg_split 与 split 函数
- PHP 正则表达式之正则处理函数小结(preg_match,preg_match_all,preg_replace,preg_split)
- preg_split()函数。该函数用正则表达式分割字符串
- PHP 正则表达式匹配 preg_match 与 preg_match_all 函数
- PHP 正则表达式匹配 preg_match 与 preg_match_all 函数
- PHP 正则表达式匹配 preg_match 与 preg_match_all 函数
- PHP 正则表达式匹配函数 preg_match 与 preg_match_all
- PHP中的正则表达式函数preg_
- \"preg_\" 为前缀的正则表达式常用操作函数——php
- python之正则表达式之简单分割字符串split()函数
- php正则表达式函数 preg_match()
- PHP 正则表达式匹配函数 preg_match 与 preg_match_all
- php正则表达式函数 preg_replace用法
- PHP 正则表达式匹配函数 preg_match 与 preg_match_all
- PHP 正则表达式匹配 preg_match 与 preg_match_all 函数
- php正则表达式函数 preg_replace用法
- (PHP)正则表达式-preg_grep函数用法
- PHP正则表达式替换函数preg_replace
- 【php】正则表达式函数preg_match用法