php正则表达式之preg_match详解

本文详细介绍了PHP中的preg_match函数,该函数用于在目标字符串中搜索指定的正则表达式模式,并仅进行一次匹配。文章通过多个示例展示了如何使用该函数,包括如何设置参数以获取匹配结果的位置信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 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] 为完全匹配的字符串, $matches[1] 匹配的字符串在目标字符串偏移下标;

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

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

 

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

 

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

 

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

 

转载于:https://www.cnblogs.com/trNote/p/7262017.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值