继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

有关正则表达式的函数

php小白兔秀秀
关注TA
已关注
手记 60
粉丝 37
获赞 648
Php中常用的正则表达式函数

preg_math($pattern,$subject);
Preg_math_all($pattern,$subject,array&$matches);
Preg_replace($pattern,$replacement,$subject);
Preg_filter($pattern,$replacement,$subject);
Preg_grep($pattern,array$input);
Preg_split($pattern,$subject);
Preg_quote($str);

准备工作:

$pattern =正则表达式;$subject = 匹配的目标数据

一个展示函数:

function show($var =null){
  if(empty($var)){
        echo 'null';
     }elseif(is_array($var)||is_object($var)){
    echo '<pre>';
    print_r($var);
    echo '</pre>';
    }
}

preg_match和preg_match_all

格式:preg_math($pattern,$subject);
Preg_math_all($pattern,$subject,array&$matches)

$pattern = '/[0-9]/';
$subject = 'weuyr3ui76as83s0ck9';
$m1 = $m2 = array();
$tt1 = preg_match($pattern,$subject,$m1);
$tt2 = preg_match_all($pattern,$subject,$m2);show($m1);
echo'<hr/>';
show($m2);
echo "<hr/>";
echo $tt1."&&".$tt2;

执行结果:

图片描述

//preg_match和preg_match_all区别
//一参数:preg_match 第三个参数是可选的,而preg_match_all的第三参数是必须有的
//二原理preg_match找到满足要求的就结束。preg_match_all找到所有符合要求的元素。
//结果:preg_match结果是一个一维数组,preg_match_all是一个二维数组
//返回值:返回个数不同。

Preg_replace和Preg_filter

格式:Preg_replace($pattern,$replacement,$subject);
Preg_filter($pattern,$replacement,$subject);
// 参数一样,原理、功能都一样。只有结果有区别。
// //要替换的词

$pattern = '/[0-9]/';
$subject = 'weuyr3ui76as83s0ck9';
$replacement = "秀秀";
$tt1=preg_replace($pattern, $replacement, $subject);
$tt2=preg_filter($pattern, $replacement, $subject);
show($tt1);
echo "<hr>";
show($tt2);

执行结果:
图片描述

$pattern =  array("/[0-2]/","/[3-5]/","/[6-8]/","/[9]/" );
$subject =array("weuy","r3u","i76as","83s0","c","k9"); 
$replacement = array("我","稀","罕","米");
$tt1=preg_replace($pattern, $replacement, $subject);
$tt2=preg_filter($pattern, $replacement, $subject);

show($tt1);
echo "<hr>";
show($tt2);

执行结果:图片描述

Preg_grep()

格式:Preg_grep($pattern,array$input);

$pattern = "/[0-9]/";
$subject =array("weuy","r3u","i76as","83s0","c","k9"); 
$tt1 = preg_grep($pattern, $subject);
show($tt1);

执行结果:
图片描述

Preg_split

格式:Preg_split($pattern,$subject);

$pattern = "/[0-9]/";
$subject = "ÎÒ3ºÃϲ45»¶7ÄãŶ£¡";

$arr=preg_split($pattern, $subject);
show($arr);

执行结果:图片描述
图片描述

preg_quote

格式:Preg_quote($str);

$str = "dddd[sss]{ssss}";
$string = preg_quote($str);
show($string);

结果:图片描述

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP