那麼,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>
的preg_replace( 「#<標籤ATTR = \」 Y \「>(+)#我「,」[tag = y] \\ 1 [/ tag]「,$ text); – Bestudio
點擊「編輯」有更多的信息來更新你的問題,這是很容易,評論閱讀。 – Jocelyn