dqrzot2791 2010-11-20 18:15
浏览 104
已采纳

preg_match搜索

<?php
$content = "
{php
    {php 1 php}
    {php 2 php}
    {php 3 php}
php}"; 

How I can get 4 strings?

First:

{php 1 php}
{php 2 php}
{php 3 php}

Second:

1

Third:

2

Four:

3
  • 写回答

2条回答 默认 最新

  • duanjucong3124 2010-11-20 22:13
    关注

    While you could easily parse such input with a simple counter, it is possible to use a recursive regex to get what you want. A simple (?) regex to validate the input would be:

    ^({php\s*(\d+|(?1)+)\s*php}\s*)$
    

    (?1) is a recursive match, it tries to match the first group again, which is another {php ... php} token. We also have a capturing group between the phps to capture their content.

    In your case you want to capture overlapping results (in fact, even results contained within other results). This is even less pretty, but still possible, using a look-ahead. Look-around can have capturing groups, so the pattern would be:

    (?=({php\s*(\d+|(?1)+)\s*php}\s*))
    

    The result has a two extra captured groups - blank results for the look around, and the whole token with the outer {php ... php}, but if you use PREG_PATTERN_ORDER your expected results will be on the third postion ([2]):

    [2] => Array
    (
        [0] => {php 1 php}
               {php 2 php}
               {php 3 php}
        [1] => 1
        [2] => 2
        [3] => 3
    )
    

    Here's a bit more complex example: http://ideone.com/sWWrT

    Now, the mandatory word of caution. As I've said earlier, this is much more readable and maintainable with a simple depth counter, you don't really need a regex here, beyond recreational use.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!