正则表达式是一种描述字符串结果的语法规则,是一个特定的格式化模式,可以匹配、替换、截取匹配的字符串。常用的语言基本上都有正则表达式,如JavaScript、java等。其实,只有了解一种语言的正则使用,其他语言的正则使用起来,就相对简单些。文本主要讲解常用的正则表达式函数和正则表达式基本语法。
一、常用的正则表但是函数
preg_match($pattern,$subject,[array&$matches])
preg_match_all($pattern,$subject,array&$matches)
preg_match($pattern,$subject,[array &$matches]) --进行正则表达式匹配
preg_match_all($pattern,$subject,array &$matches) --进行正则表达式匹
实例代码:
$pattern = '/[0-9]/';
$subject = 'weuyr3ui76as83s0ck9';
$m1 = $m2 = array();
$t1 = preg_match($pattern, $subject,$m1);
$t2 = preg_match_all($pattern, $subject,$m2);
print_r($m1);
echo "
";
print_r($m2);
echo $t1.'||'.$t2;
结果:
Array ( [0] => 3 )
Array
(
[0] => Array
(
[0] => 3
[1] => 7
[2] => 6
[3] => 8
[4] => 3
[5] => 0
[6] => 9
)
)
1||7;
preg_replace($pattern, $replacement, $subject)
preg_filter($pattern, $replacement, $subject)
preg_replace($pattern, $replacement, $subject) --执行正则表达式的搜索和替换
preg_filter($pattern, $replacement, $subject) --执行正则表达式的搜索和替换
实例代码:
// $pattern = '/[0-9]/';
// $subject = 'weuyr3ui76as83s0ck9';
// $replacement = "小学生";
// $str1 = preg_replace($pattern, $replacement, $subject);
// $str2 = preg_filter($pattern, $replacement, $subject);
// echo "";
// print_r($str1);
// echo "
";
// print_r($str2);
/* ********************输出的结果***********************
weuyr小学生ui小学生小学生as小学生小学生s小学生ck小学生
weuyr小学生ui小学生小学生as小学生小学生s小学生ck小学生
*/
// $pattern = array('/[0123]/','/[456]/','/[789]/');
// $subject = 'weuyr3ui76as83s0ck9';
// $replacement = array("小","学","生");
// $str1 = preg_replace($pattern, $replacement, $subject);
// $str2 = preg_filter($pattern, $replacement, $subject);
// echo "";
// print_r($str1);
// echo "
";
// print_r($str2);
/* ********输出的结果********
weuyr小ui生学as生小s小ck生
weuyr小ui生学as生小s小ck生
*/
//*********************区别*********************
$pattern = array('/[0123]/','/[456]/','/[789]/');
$subject = array('weuy','r3ui','76as83','s0ck9');
$replacement = array("小","学","生");
$str1 = preg_replace($pattern, $replacement, $subject);
$str2 = preg_filter($pattern, $replacement, $subject);
echo "";
print_r($str1);
echo "
";
print_r($str2);
/*
结果:
Array
(
[0] => weuy
[1] => r小ui
[2] => 生学as生小
[3] => s小ck生
)Array
(
[1] => r小ui
[2] => 生学as生小
[3] => s小ck生
)
注意:
preg_replave() --不管字符串有没有发生变化全都会保留。
preg_filter() --只会保留发生过替换的字符串。
preg_grep()
preg_grep() --返回匹配模式的数组条目(只做匹配,不做替换)
实例代码:
$pattern = '/[0-9]/';
$subject = array('weuy','r3ui','76as83','s0ck9');
$arr = preg_grep($pattern, $subject);
echo "";
print_r($arr);
结果:
Array
(
[1] => r3ui
[2] => 76as83
[3] => s0ck9
)
preg_split($psttern,$subject)
preg_split($psttern,$subject) --通过一个正则表达式分隔字符串
实例代码:
$pattern = '/[0-9]/';
$subject = '小2学3生,7约吗?';
$arr = preg_split($pattern, $subject);
echo "";
print_r($arr);
结果:
Array
(
[0] => 小
[1] => 学
[2] => 生,
[3] => 约吗?
)
preg_quote($str)
preg_quote($str) --正则运算符转义
实例代码:
$str = 'qwer{asdf}[1234]';
$str= preg_quote($str);
echo $str;
结果:
qwer\{asdf\}\[1234\]