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