嗯,PHP 的正则表达式实现支持 PCRE 的递归模式。但是,由于其神秘的性质,我会犹豫使用这样的功能。但是,既然你问:
不使用扩展?
这里是:
<?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);
?>
这将打印以下内容:
<tag attr="z">
[tag=y]
<tag>
<tag attr="more" stuff="here">
<tag attr="x"></tag>
</tag>
</tag>
[/tag]
</tag>