Welcome 微信登录

首页 / 网页编程 / PHP / 模式修正符

模式修正符2017-01-25 本站 guaitu模式修正符是为正则表达式增强和补充的一个功能,使用在正则表达式之外,是这种形式:/正则表达式/U

i: 正则内容在匹配的时候不区分大小写

<?php
header("content-type: text/html;charset=utf-8");
$mode="/www.bianceng.cn/i"; //i修饰符的意思是不区分大小写,匹配成功
$string="WWW.BIANCENG.CN";
/*区分大小写,匹配失败
$mode="/www.bianceng.cn/";
$string="WWW.BIANCENG.CN";
*/
if(preg_match($mode,$string)){
echo "匹配成功!";
}else{
echo "不匹配!";
}
?>
m: 在匹配首内容或者尾内容时采用多行识别匹配

<?php
header("content-type: text/html;charset=utf-8");
//使用m开启多行识别匹配, 前的内容看作一行,匹配成功
$mode="/php$/m";
$string="This is php ,very good";
/**没有使用m开启多行识别匹配
***把$string中的内容看作一个字符串,与末尾匹配,匹配失败
$mode="/php$/";
$string="This is php ,very good";
*/
if(preg_match($mode,$string)){
echo "匹配成功!";
}else{
echo "不匹配!";
}
?>
x:忽略正则中的空白

<?php
header("content-type: text/html;charset=utf-8");
//x忽略正则中的空白,匹配成功
$mode="/ph p/x";
$string="php";
$string="This is php ,very good";
if(preg_match($mode,$string)){
echo "匹配成功!";
}else{
echo "不匹配!";
}
?>
A: 强制从头开始匹配

<?php
header("content-type: text/html;charset=utf-8");
//A强制从头匹配,匹配失败
$mode="/php/A";
$string="This is php";
if(preg_match($mode,$string)){
echo "匹配成功!";
}else{
echo "不匹配!";
}
?>
U: 禁止贪婪匹配,只跟踪到最近的一个匹配符并结束

贪婪匹配:匹配到最后一个匹配符:

例:

<?php
header("content-type: text/html;charset=utf-8");
//贪婪和分组获取的案例,ubb
//将[b]php5[/b]换成<strong>php5</strong>
//用括号分组,(.*)就是1
$mode = "/[b](.*)[/b]/";
$replace = "<strong>1</strong>";
$string = "This is a [b]php5[/b]. This is a [b]php4[/b]";
echo preg_replace($mode,$replace,$string);
?>
输出:This is a php5[/b]. This is a [b]php4

使用U禁止贪婪匹配,让[b]与最近的[/b]匹配:

<?php
header("content-type: text/html;charset=utf-8");
//将[b]php5[/b]换成<strong>php5</strong>
//用括号分3组,(.*)就是2
$mode = "/([b])(.*)([/b])/U";
$replace = "<strong>2</strong>";
$string = "This is a [b]php5[/b]. This is a [b]php4[/b]";
echo preg_replace($mode,$replace,$string);
?>
输出:

This is a php5. This is a php4

URL: http://www.bianceng.cn/webkf/PHP/201701/50536.htm