今天修改代码时读到别人写的一段代码preg_match_all的使用,顺便查阅了一下正则,下面谈谈这个函数的学习心得。
首先看下preg_match_all的定义
int preg_match_all ( string $pattern
, string $subject
, array $matches
, int $flags
= PREG_PATTERN_ORDER
)
$pattern:要匹配的字符串,一般为正则表达式
$subject:源数据
$matches:匹配完之后的结果集,是array类型
$flag:PREG_PATTERN_ORDER
和 PREG_SET_ORDER 稍后会介绍两种不同
例子1:
<?php
preg_match_all("|<[^>]+>(.*)</[^>]+>|U",
"<b>example: </b><div align=left>this is a test</div>",
$out, PREG_PATTERN_ORDER);
echo $out[0][0] . ", " . $out[0][1] . "\n";
echo $out[1][0] . ", " . $out[1][1] . "\n";
?>
结果:
<b>example: </b>, <div align=left>this is a test</div> example: , this is a test例子2:
<?php
preg_match_all("|<[^>]+>(.*)</[^>]+>|U",
"<b>example: </b><div align=\"left\">this is a test</div>",
$out, PREG_SET_ORDER);
echo $out[0][0] . ", " . $out[0][1] . "\n";
echo $out[1][0] . ", " . $out[1][1] . "\n";
?>
结果:
<b>example: </b>, example: <div align="left">this is a test</div>, this is a test通过这两个php官方手册例子可以了解这个函数的基本用法。
下面具体讲一下正则参数,首先知道: |U表示非贪婪匹配,即匹配一条数据之后就保存输入 详细请看正则标志的用法
string $pattern
例1:
"|<[^>]+>(.*)</[^>]+>|U"
首先匹配整个字符串,然后注意()中的部分,将匹配之后追加保存。 一般我们都是需要获取()中的值,可以通过返回的数组获取。
通过下面的例子我们来理解一下:
1:带有贪婪匹配的
preg_match_all("/today=(.*) /U", "today=2013-06-20 today=2013-06-21 ", $out, PREG_SET_ORDER);
var_dump($out);exit;
返回结果是:
array(2) {
[0]=>
array(2) {
[0]=>
string(17) "today=2013-06-20 "
[1]=>
string(10) "2013-06-20"
}
[1]=>
array(2) {
[0]=>
string(17) "today=2013-06-21 "
[1]=>
string(10) "2013-06-21"
}
}
2:不带有贪婪匹配的
preg_match_all("/today=(.*) /", "today=2013-06-20 today=2013-06-21 ", $out, PREG_SET_ORDER);
var_dump($out);exit;
array(1) {
[0]=>
array(2) {
[0]=>
string(34) "today=2013-06-20 today=2013-06-21 "
[1]=>
string(27) "2013-06-20 today=2013-06-21"
}
}