PHP 的正则相关函数总结

来源:互联网 发布:32位ubuntu镜像下载 编辑:程序博客网 时间:2024/05/16 16:03

正则程序员基本都会用到,但是用的都不多,本文总结、比较 PHP 常用的正则函数:

1. preg_match 和 preg_match_all

preg_match 与 preg_match_all 都是用来匹配正则表达式。

主要参数有三个:preg_match_all ( string patt,stringstr , array $matches);

$patt: 正则表达式。

$str: 匹配的字符串。

matches:matches)。

区别:preg_match_all 输出所有匹配结果。 preg_match 默认输出第一个匹配结果。

例如:

$str = 'hi,this is his history';$patt = '/\bhi/';preg_match_all($patt,$str,$matches);var_dump($matches);preg_match($patt,$str,$matches);var_dump($matches);

输出结果:

array (size=1)  0 =>     array (size=3)      0 => string 'hi' (length=2)      1 => string 'hi' (length=2)      2 => string 'hi' (length=2)array (size=1)  0 => string 'hi' (length=2)

可选参数:flagsoffset 字符串偏移量。

2.preg_replace , preg_replace_callback和 preg_filter

这几个函数都是利用正则替换字符串的。原理都是先用正则匹配字符串,然后将匹配到的结果替换成目标字符串,返回替换后的字符串。

preg_replace ( patt,replacement , $str );

$patt: 匹配正则表达式。

$replacement:要替换成的目标字符。

$str: 原始字符串。

例如:

$str = 'hi,this is his history';$patt = '/\bhi/';$str = preg_replace($patt,'hollow',$str);echo $str;

输出:

hollow,this is hollows hollowstory

preg_replace_callback 即是将第二个参数换成一个方法。

例如:

$text = "April fools day is 04/01/2002\n";$text.= "Last christmas was 12/24/2001\n";function next_year($matches){  return $matches[1].($matches[2]+1);}echo preg_replace_callback(            "|(\d{2}/\d{2}/)(\d{4})|",            "next_year",            $text);

preg_filter 的用法与preg_replace相同。

3. preg_grep

正则匹配一组数组,返回数据中符合正则的元素数组。

$arr = ['hi','hollow','show'];$patt = '/ho/';$z = preg_grep($patt,$arr);print_r($z);

返回:

Array ( [1] => hollow [2] => show )

4.preg_split 分割字符串

通过一个正则表达式分隔给定字符串.

preg_splite( pattern,str , limit,flags )

$pattern : 正则表达式。

$str : 原字符串。

$limit : 最大保留截断数。(可选)

$flags: 返回集合(可选)

例:

$keywords = preg_split("/[\s,]+/", "hypertext language, programming");print_r($keywords);

输出:

Array(    [0] => hypertext    [1] => language    [2] => programming)
原创粉丝点击