preg_match与preg_match_all 第四及第五个参数详解

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

preg_match 在目标字符串中搜索指定模式(你给的正则表达式),只匹配一次,匹配上了就马上停止搜索返回结果--它的值将是0次(不匹配)或1次。

参数列表:

pattern 要搜索的模式 ;

subject : 目标字符串;

matches: 如果提供了参数matches,它将被填充为搜索结果,$matches[0] 为完全匹配的字符串

flags:可选PREG_OFFSET_CAPTURE (值256),如果设置为PREG_OFFSET_CAPTURE,那么$matches[1]将会填充匹配的字符串在目标字符串偏移下标;

比如:

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(17) "第130章  群龙"
    [1]=>
    int(5948)
  }
  [1]=>
  array(2) {
    [0]=>
    string(24) "第129章   天下变了"
    [1]=>
    int(6025)
  }
}

offset: 通常搜索目标字符串是从最左边开始,设置offset后,将会从设定的偏移量开始搜索;(offset的单位是字节,一个中文是3个字节)

 

 $subject = "abcdefGHijdef";
 $pattern = '/def/';
 //preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
 $ret= preg_match($pattern, $subject, $matches);
 print_r($matches);//结果:  Array ( [0] => def )
 print_r($ret);//结果为1
 $subject = "abcdefGHijdef";
 $pattern = '/def/';
 //使用了PREG_OFFSET_CAPTURE参数后,$mathces填充了匹配的偏移信息
 preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);
 print_r($matches);//结果: Array ( [0] => Array ( [0] => def [1] => 3 ) )

 

$subject = "defabcdefGH";
$pattern = '/def/';
//设置了offset后跳过了第一个def去搜索匹配,匹配的结果是目标字符串中的第二个def,偏移位置为6
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE,3);
print_r($matches);//结果:Array ( [0] => Array ( [0] => def [1] => 6 ) )

 

$subject = "我我abcf";
$pattern = '/我/';
//offset设置偏移第一个中文“我”
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE,3);
print_r($matches);//Array ( [0] => Array ( [0] => 我 [1] => 3 ) )

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值