preg_match()、preg_match_all()、preg_replace 与 preg_filter
1、preg_match ( $pattern, $subject, [ array &$matchs ] ); //执行匹配正则表达式
2、preg_match_all ( $pattern, $subject, array &$matches ); //执行一个全局正则表达式匹配
返回结果:匹配到结果的次数;
参数说明:
pattern 要搜索的模式,字符串类型
subject 输入字符串
matches 对于第一个函数,如果提供了参数matches,它将被填充为搜索结果。$matches[0]将包含完整模式匹配到的文本,$matches[1] 将包含捕获子组匹配到的文本。
对于第二个函数,matches是必填项,它是一个多维数组,作为输出参数输出所有匹配结果, 数组排序通过flags
指定。
3、preg_replace ( $pattern, $replacement, $subject ) //执行一个正则表达式的搜索和替换
4、preg_filter ( $pattern, $replacement, $subject ) //执行一个正则表达式搜索和替换
参数说明:
pattern 要搜索的模式。可以使一个字符串或者字符串数组。可以使用PCRE修饰符
replacement 用于替换的字符串或者字符串数组。
subject 要进行搜索和替换的字符串或字符串数组。
区别:preg_filter 它仅仅返回(可能经过转化)与目标匹配的结果,功能和preg_replace类似
返回值:如果subject
是一个数组,返回一个数组, 其他情况返回一个字符串。
如果没有找到匹配或者发生了错误,当subject
是数组 时返回一个空数组,其他情况返回NULL
。
5、preg_grep ( $pattern, array $input ) // 返回匹配模式的数组条目
只做匹配,不做替换,是preg_filter的简版;
参数说明:
pattern 要搜索的模式,字符串形式
input 输入数组
通过demo查看效果:
1
2
3
4
|
$pattern = '/[0-9]/' ;
$subject = [ 'afddd' , 'd3asf' , 's4' , 'as' , '9as' , 'f1' ];
$str1 = preg_grep($pattern, $subject); show($str1); |
结果:
1
2
3
4
5
6
7
|
Array ( [1] => d3asf
[2] => s4
[4] => 9as
[5] => f1
) |
6、preg_split ( $pattern, $subject ) // 通过一个正则表达式分隔字符串
说明:通过正则表达式匹配字符串,将字符串按正则拆分成数组,如果你不需要正则表达式功能,可以有更快(并且更简单)的选择比如 explode() 或 str_split()。如果没有成功匹配,将会返回一个数组,包含了单个元素,即输入的字符串。
参数说明:
pattern 用搜索的模式,字符串形式。
subject 输入字符串