<?php //1.搜索数组中的相匹配的字符串 //preg_grep() 返回一个数组 $language = array("php","asp","jsp","python","ruby"); //找出jsp,asp,php => 结尾匹配P $model = "/p$/"; print_r(preg_grep($model, $language)); echo "<hr>"; //打印出开头为P $model = "/^p/"; print_r(preg_grep($model, $language)); echo "<hr>"; //2.搜索模式,返回真或假。1,0; //preg_match(); echo(preg_match("/php[1-6]/", "php7")); echo(preg_match("/php[1-6]/", "php2")); echo "<hr>"; //电子邮件的小案例 $model = "/([\w]{2,255})@([\w]{1,255})\.([a-z]{2,4})/"; $email = "1056834607@qq.com"; echo (preg_match($model, $email)); $model = "/([\w]{2,255})@([\w]{1,255})\.([a-z]{2,4})/"; $email = "gaoxiong@qqvvvvvvvvvvvvvv.xin"; $model = "/([\w]{2,255})@([\w]{1,255})\.([a-z]{3,4})/"; $email = "arraybuffer@foxmail.com"; echo (preg_match($model, $email))."<hr>";//1 //3.全局正则表达式匹配 //preg_match_all()将字符串的所有匹配得到的结果放到一个数组 preg_match_all("/php[1-6]/", "php5fffffphp6cccccphp3", $out); print_r($out);//$out是一个二位数组 echo "<hr>"; //4.定界正则 // preg_quote()在内阁对于正则表达式语法而言有特俗含义的字符前插入一个反斜线,这些特俗字符包含:$ ^ * () [] {} | \\:<> echo(preg_quote("this is $50"))."<hr>"; //5.替换模式 //preg_replace()搜索到所有匹配,然后替换成想要的字符串返回出来 echo preg_replace("/php[1-6]/", "python", "this is php5, this is php4")."\n<hr>"; //6.贪婪和分组获取案例 $model = '/\[b\](.*)\[\/b\]/U'; $replace = '<strong>\1</strong>';//必须使用单引号 $string = "this is [b]xiong[/b], this is [b]xiong[/b] "; echo preg_replace($model, $replace, $string)."\n<hr>"; $model = '/<span>(.*)<\/span>/U'; $replace = '<strong>\1</strong>';//必须使用单引号 $string = 'this is <span>xiong</span>, this is <span>xiong</span>'; echo preg_replace($model, $replace, $string)."<hr>"; //6.以不区分大小写的方式来划分不同的元素 //preg_split() 返回一个数组 print_r(preg_split("/[\.@]/", "arraybuffer@qq.com")) ?>