PHP, nested templates in preg_replace

前端 未结 4 1523
广开言路
广开言路 2021-01-13 21:41
preg_replace(\"/\\[b\\](.*)\\[\\/b\\]/Usi\", \"$1\", \"Some text here... [b][b]Hello, [b]PHP![/b][/b][/b] ... [b]and here[/b]\");
         


        
4条回答
  •  半阙折子戏
    2021-01-13 22:24

    Yes, a multi-pass approach is required if the elements are nested. This can be accomplished in one of two ways; matching from the inside out or from the outside in. Here are two tested scripts with fully commented regexes which illustrate each technique:

    1. Replace from the inside out:

    $1', $text);
        printf("i[%d]=%s", $i++, $text);
    }
    ?>
    

    Output:

    '''
    Replace matching tags from the inside out:
    i[0]=Some text here... [b][b]Hello, [b]PHP![/b][/b][/b] ... [b]and here[/b]
    i[1]=Some text here... [b][b]Hello, PHP![/b][/b] ... and here
    i[2]=Some text here... [b]Hello, PHP![/b] ... and here
    i[3]=Some text here... Hello, PHP! ... and here
    '''
    

    2. Replace from the outside in:

    $1', $text);
        printf("i[%d]=%s", $i++, $text);
    }
    ?>
    

    Output:

    '''
    Replace matching tags from the outside in:
    i[0]=Some text here... [b][b]Hello, [b]PHP![/b][/b][/b] ... [b]and here[/b]
    i[1]=Some text here... [b]Hello, [b]PHP![/b][/b] ... and here
    i[2]=Some text here... Hello, [b]PHP![/b] ... and here
    i[3]=Some text here... Hello, PHP! ... and here
    '''
    

    Note the (?R) recursive expression used in the second approach.

提交回复
热议问题