PHP正则表达式组捕获 [英] PHP regex groups captures

查看:88
本文介绍了PHP正则表达式组捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下正则表达式:

\[([^ -\]]+)( - ([^ -\]]+))+\]

这与以下内容成功匹配:

This match the following successfully:

[abc - def - ghi - jkl]

但匹配项是:

Array
(
    [0] => [abc - def - ghi - jkl]
    [1] => abc
    [2] =>  - jkl
    [3] => jkl
)

我需要的是这样的东西:

What I need is something like this:

Array
(
    [0] => [abc - def - ghi - jkl]
    [1] => abc
    [2] =>  - def
    [3] => def
    [4] =>  - ghi
    [5] => ghi
    [6] =>  - jkl
    [7] => jkl
)

我可以在C#中通过查看捕获"组来做到这一点.如何在PHP中做到这一点?

I'm able to do that in C# looking at the groups "captures". How can I do that in PHP?

推荐答案

这不是regexp的工作.与\[([^\]]*)\]匹配,然后由" - "匹配split第一次捕获.

This is not the job for the regexp. Match against \[([^\]]*)\], then split the first capture by the " - ".

<?php                                                                       
  $str = "[abc - def - ghi - jkl]";
  preg_match('/\[([^\]]*)\]/', $str, $re);
  $strs = split(' - ', $re[1]);
  print_r($strs);
?>

这篇关于PHP正则表达式组捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆