php之正则表达式函数总结

php之正则表达式函数总结

  • 匹配

    用于匹配常用的函数有两个,分别是preg_matchpreg_match_all

看代码:

//preg_match($pattern, $subject, &$match, [$flags=0], [$offset=0]) 一般三个参数

$pattern = '/[0-9]/';  //正则
$subject = 'abc1def2ghi3klm4';    //需要匹配的字符串
$return = preg_match($pattern, $subject, $matches);
echo $return; //1  因为匹配到了1个就会停止匹配
print_r($matches); // ['1']  将所有满足正则规则的匹配放到数组里。


//preg_match_all($pattern, $subject, $matches,...)
$pattern = '/[0-9]/';//正则字符串
$subject = 'abc1def2ghi3klm4';//需要匹配的目标字符串
$return = preg_match_all($pattern, $subject, $matches);
echo $return;//4    因为会匹配所有的
print_r($matches);//[0=>['1','2','3','4']] 注意是个二维数组。
  • 替换

    用于替换常用的函数也有两个preg_replacepreg_filter,这两个灰常的相似!!!

看代码:

//preg_replace($pattern, $replacement, $subject)

$pattern = '/[0-9]/';
$replacement = '嘿嘿嘿';
$subject = 'a1b2c3';
$return = preg_replace($pattern, $replacement, $subject);
echo $return; //'a嘿嘿嘿b嘿嘿嘿c嘿嘿嘿'


//preg_filter($pattern, $replacement, $subject)     //和preg_replace 没有任何变化
$pattern = '/[0-9]/';
$replacement = '嘿嘿嘿';
$subject = 'a1b2c3';
$return = preg_filter($pattern, $replacement, $subject);
echo $return; //'a嘿嘿嘿b嘿嘿嘿c嘿嘿嘿'

//但是$pattern 和 $subject都是数组呢
$pattern = array('/[0-3]/', '/[4-6]/', '/[7-9]/');
$replacement = array('小', '中', '大');
$subject = array('a', 'b', '1as', 'd', 's5d', '7qq');
$return = preg_replace($pattern, $replacement, $subject);
print_r($return);
//结果
Array
(
    [0] => a
    [1] => b
    [2] => 小as
    [3] => d
    [4] => s中d
    [5] => 大qq
) 


$pattern = array('/[0-3]/', '/[4-6]/', '/[7-9]/');
$replacement = array('小', '中', '大');
$subject = array('a', 'b', '1as', 'd', 's5d', '7qq');
$return = preg_filter($pattern, $replacement, $subject);
print_r($return);
//结果
Array
(
    [2] => 小as
    [4] => s中d
    [5] => 大qq
)
  • 数组匹配 + 分割

    分别是preg_greppreg_split

看代码:

//趁热打铁  其实preg_grep呢 就是preg_filter的阉割版  只匹配  不替换而已
//preg_grep($pattern, $subject)
$subject = ['r', 'a2', 'b3', 'c', 'd'];
$pattern = '/[0-9]/';
$fl_array = preg_grep($pattern, $subject);
print_r($fl_array);
//结果:
Array
(
    [1] => a2
    [2] => b3
)    //注意索引


//preg_split($pattern, $subject) 返回分割后的数组
$subject = 'a132b456c777d';
$pattern = '/[0-9]+/';   匹配至少一个数字
$return = preg_split($pattern, $subject);
print_r($return);
//结果:
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)

相关推荐