PHP, nested templates in preg_replace

前端 未结 4 1522
广开言路
广开言路 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

    The reason it doesn't work: You catch the first [b], then move on to the next [/b], and leave anything in between unchanged. Ie, you change the outer [b] tags, but not the ones nested inside.

    Your comment to @meza suggests you want to replace the pseudo tags in pairs, or else leave them untouched. The best way to do this is to use multiple passes, like this

    $markup = "Some text here... [b][b]Hello, [b]PHP![/b][/b][/b] ... [b]and here[/b]";
    $count = 0;
    do {
        $markup = preg_replace("/\[b\](.*?)\[\/b\]/usi", "$1", $markup, -1, $count );
    } while ( $count > 0 );
    
    print $markup;
    

    I'm not even sure if you can do it in a one-line regex, but even if you could, it would be rather complex and therefore hard to maintain.

提交回复
热议问题