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 ) )