preg_match_all使用

今天修改代码时读到别人写的一段代码preg_match_all的使用,顺便查阅了一下正则,下面谈谈这个函数的学习心得。

首先看下preg_match_all的定义

int preg_match_all ( string $pattern , string $subject , array $matchesint $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"
  }
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值