什么是捕获组
捕获组就是把正则表达式中子表达式匹配的内容,保存到内存中以数字编号或显式命名的组里,方便后面引用。当然,这种引用既可以是在正则表达式内部,也可以是在正则表达式外部。
索引数组eg:
$str='/meteoric_cry/archive/2011/01/22/1942032';
$regex='#^/(meteoric_cry)/(\w+)/([0-9]+)/([0-9]+)/([0-9]+)/([0-9]+)$#i';
preg_match($regex,$str,$matches);
var_dump($matches);
//输出
array (
0 => '/meteoric_cry/archive/2011/01/22/1942032',
1 => 'meteoric_cry',
2 => 'archive',
3 => '2011',
4 => '01',
5 => '22',
6 => '1942032',
)
关联数组eg:
$str='/meteoric_cry/archive/2011/01/22/1942032';
$regex='#^/(?<meteoric_cry>meteoric_cry)/(?<type>\w+)/(?<year>[0-9]+)/(?<month>[0-9]+)/(?<day>[0-9]+)/(?<id>[0-9]+)$#i';
preg_match($regex,$str,$matches);
var_dump($matches);
//输出
array(13) {
[0]=>
string(40) "/meteoric_cry/archive/2011/01/22/1942032"
["meteoric_cry"]=>
string(12) "meteoric_cry"
[1]=>
string(12) "meteoric_cry"
["type"]=>
string(7) "archive"
[2]=>
string(7) "archive"
["year"]=>
string(4) "2011"
[3]=>
string(4) "2011"
["month"]=>
string(2) "01"
[4]=>
string(2) "01"
["day"]=>
string(2) "22"
[5]=>
string(2) "22"
["id"]=>
string(7) "1942032"
[6]=>
string(7) "1942032"
}
用于 : 无法用,和"" 分割含有json的字符串
$str = '"20191014","10098877","가시나무검객","1571022530","{"install_time":"2019-10-14 02:59:20.186","campaign_id":"6671503174","lat":"0"}"';
$regex = '/^"([^"]*)","([^"]*)","([^"]*)","([^"]*)","(.*)"$/';
if(preg_match($regex, $str, $matches)){
print_r($matches);
}
//输出
Array
(
[0] => "20191014","10098877","가시나무검객","1571022530","{"install_time":"2019-10-14 02:59:20.186","campaign_id":"6671503174","lat":"0"}"
[1] => 20191014
[2] => 10098877
[3] => 가시나무검객
[4] => 1571022530
[5] => {"install_time":"2019-10-14 02:59:20.186","campaign_id":"6671503174","lat":"0"}
)