一、preg_match 与 prge_match_all
preg_match($pattern, $subject, [array &$matches])
preg_match_all($pattern, $subject, array &$matches)
$pattern:正则表达式
$subject:匹配的目标数据
&$matches:把匹配的数组放置在 match 数组中(引用传递,在函数内部操作的 macth 数组是直接操作在函数外部定义的数组)
返回:匹配到的结果的次数
实例:
$pattern = '/[0-9]/';
$subject = 'l0u7lub2lo9g4';
$m1 = $m2 = [];
preg_match($pattern, $subject, $m1);
preg_match_all($pattern, $subject, $m1);
返回:
二、preg_replace 与 preg_filter
preg_replace($pattern, $replacement, $subject)
preg_filter($pattern, $replacement, $subject)
将匹配到的返回到 replacement 中
实例:
$pattern = ['/[0123]/','/[456]/','/[789]/'];
$subject = ['lulu','bl3og','4lbo9','b','0log'];
$replacment = ['鲁','鲁','槟'];
$str1 = preg_replace($pattern, $replacment, $subject);
$str2 = preg_filter($pattern, $replacment, $subject);
返回:
分析返回结果可知:preg_replace 保留全部字符串,preg_filter 只会保留发生替换的字符串
三、preg_grep
preg_grep($pattern, array input)
阉割版的 preg_filter(),只会匹配不做替换
实例:
$pattern = '/[0-9]/';
$subject = ['lulu','bl3og','4lbo9','b','0log'];
$arr = preg_grep($pattern, $subject);
返回:
四、preg_split
preg_split($pattern, $subject)
将 $subject 按 $pattern 分割字符串
实例:
$pattern = '/[0-9]/';
$subject = 'lulu3blo6g,5约吗?';
$arr = preg_split($pattern, $subject);
返回:
五、preg_quote
preg_quote($str)
正则运算符转义
实例:
$str= '/lulu{blog}[520]/';
$res = preg_quote($str);
返回: