下面从简单慢慢列举正则的语法,用法。同学前辈们可以借鉴学习

<?php
/**
正则表达式学习
preg_match(模式,内容,接收匹配内容);【单次匹配】
preg_match_all(模式,内容,接收匹配内容)【全局匹配】
返回值:前者是一维数组,后者是二维数组
*/
//1-223.0-255.0-255.0-255匹配ip地址
//1-223(.0-255){3}
$num = 500;
$mode = "/^([1-9]|[1-9]\d|1\d\d|2[01]\d|22[0-3])$/";
preg_match($mode, $num, $out);
print_r($out);
exit;

//preg_grep(模式,目标数组)从指定的数组里边找到想要的元素出来
$_arr = array('apple','123','egg','456','pear','789','banana');
$mode = "/\d+/";
print_r(preg_grep($mode, $_arr));
exit;

//preg_split(模式,目标内容)将字符串拆分为更小的信息单元
//explode
$_str = "this is,bawei@school,and I,am,here'study";
$mode = "/\s|,|@|'/";
print_r(preg_split($mode, $_str));
exit;

/*
str_replace()
preg_replace(被替换内容,替换内容,字符串)
1.preg_replace(单个模式,单个内容,字符串);
2.preg_replace(数组模式,单个内容,字符串);
3.preg_replace(数组模式,数组内容,字符串);
*/
$_str = "this is sunday";
//1.echo preg_replace('/\bis\b/','was',$_str);
//$arr = array('/\Bis\b/','/\bis\b/');
//2echo preg_replace($arr, 'are', $_str);
//$arr1 = array('/\Bis\b/','/\bis\b/');
//$arr2 = array('ese','was');
//3echo preg_replace($arr1, $arr2, $_str);
exit;

//$_str = "<div>abc</div>";
//$mode = "/<(.*)>/U";
//preg_match_all($mode, $_str, $out);
//print_r($out);
//exit;

//$_str = "2010-10-20";
//$mode = "/\d{4}(\W)\d{2}\\1(\d{2})/";

//模式修正符(i大小 m多行 s单行 x忽略空白 U就近匹配 e)
//e 将替换字符串当做表达式使用
//字符串替换函数str_replace(被替换内容,替换内容,字符串);
//正则表达式替换函数preg_replace(被替换内容,替换内容,字符串);
//$_str = "this is sunday";
//echo preg_replace('/\bis\b/e','mt_rand(100,999)',$_str);
//exit;

//就近匹配,防止贪婪匹配
//$_str = "<div>abc</div>";
//$mode = "/<.*>/U";

//忽略模式中的空白
//$_str = "google";
//$mode = "/goo  g l e/x";

//将匹配内容当做单行看待,这时"."可以匹配换行符号\n
//$_str = "apple\negg";
//$mode = "/^.*$/s";

//m将匹配内容视为多行
//$_str = "apple\negg";
//$mode = "/apple$/m";

//i忽略大小写
//$_str = "GooGle";
//$mode = "/[a-z]+/i";

//()重复使用模式单元
//$_str = "2010-11-20";// 2010/11/20
//$mode = "/(\d{4})(\W)\d{2}\\2\d{2}/";

//$_str = "booak";
//$mode = "/[^abcde]/";//a|b|c|d|e

//$_str = "this is book";
//$mode = "/\bis\b/";//\b匹配单词的边界
//$mode = "/\Bis\b/";//\B匹配单词内部

//$_str = "123456abcd";
//$mode = "/[0-9]+/";

preg_match($mode, $_str, $out);
print_r($out);
?>

<?php
/**
正则表达式学习
*/
//模式单元重复使用()
$_str = "April 30,2011"; //2011 April 30   20111 April 30
$mode = "/^([a-z]+)\s(\d{2}),(\d{4})$/i";
echo preg_replace($mode, '${3}1 $1 $2', $_str);
exit;

//$_str = "select name from user order by id";
//$_str = "select title from user order by id";
//$_str = "select content from user order by id";
$_str = "select name,content from user order by id";
//【select count(*) as cnt from user order by id】
$mode = "/^select .* from .*$/";

echo preg_replace('/^(select) .* (from .*)$/', '$1 count(*) as cnt $2', $_str);
exit;

//$_str = "2010-10-20";
//$mode = "/^\d{4}(\W)\d{2}\\1\d{2}$/";   //  \\1

preg_match($mode, $_str, $out);
print_r($out);
//array(
//    [0]=>2010-10-20
//    [1]=>-
//);
?>