PHP正则表达式捕获组

什么是捕获组

捕获组就是把正则表达式中子表达式匹配的内容,保存到内存中以数字编号或显式命名的组里,方便后面引用。当然,这种引用既可以是在正则表达式内部,也可以是在正则表达式外部。

索引数组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"}
)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值