Bestudio
Bestudio

Reputation: 13

PHP BBCode regex replacement

How can I replace:

<tag attr="z">
    <tag attr="y">
        <tag attr="x"></tag>
    </tag>
</tag>

to:

<tag attr="z">
    [tag=y]
        <tag attr="x"></tag>
    [/tag]
</tag>

Without using extensions?

I unsuccessfully tried:

preg_replace("#<tag attr=\"y\">(.+?)</tag>#i", "[tag=y]\\1[/tag]", $text);

Upvotes: 1

Views: 481

Answers (1)

Bart Kiers
Bart Kiers

Reputation: 170178

Well, PHP's regex implementation supports PCRE's recursive patterns. However, I'd hesitate to use such a feature because of its cryptic nature. However, since you asked:

Without using extensions?

here it is:

<?php

$html = '<tag attr="z">
    <tag attr="y">
        <tag>
            <tag attr="more" stuff="here">
                <tag attr="x"></tag>
            </tag>
        </tag>
    </tag>
</tag>
';

$attr_regex = "(?:\s+\w+\s*=\s*(?:'[^']*'|\"[^\"]*\"))";
$recursive_regex = "@
    <tag\s+attr=\"y\">         # match opening tag with attribute 'y'
    (                          # start match group 1
      \s*                      #   match zero or more white-space chars
      <(\w+)$attr_regex*\\s*>  #   match an opening tag and store the name in group 2
      (                        #   start match group 3
        [^<]+                  #     match one or more chars other than '<'
        |                      #     OR
        (?1)                   #     match whatever the pattern from match group 1 matches (recursive call!)
      )*                       #   end match group 3
      </\\2>                   #   match the closing tag with the same name stored in group 2
      \s*                      #   match zero or more white-space chars
    )                          # end match group 1
    </tag>                     # match closing tag
    @x";

echo preg_replace($recursive_regex, "[tag=y]$1[/tag]", $html);

?>

which will print the following:

<tag attr="z">
    [tag=y]
        <tag>
            <tag attr="more" stuff="here">
                <tag attr="x"></tag>
            </tag>
        </tag>
    [/tag]
</tag>

Upvotes: 2

Related Questions