重複子模式會重複其中包含的條件式,並在每次迭代時更新子模式匹配。
考慮以下程式碼,它掃描 HTML 並追蹤角括號「<」和「>」。如果匹配到左括號「<」,則在重複可能結束之前必須接著匹配右括號「>」。這樣,正規表示式將只會有效地匹配標籤以外的內容。
<?php
$pattern='%(*ANY)(.*?(<)(?(2).*?>)(.*?))*?\'\'%s';
$replace='\1Fred';
$subject=
'<html><body class=\'\'>\'\' went to '\'\meyer and ran
into <b>\'\'</b>.
</body></html>'
echo preg_replace("%(*ANY)(.*?((<)(?(3).*?>).*?)*?)\'\'%s",'\1Fred',$subject);
?>
輸出將是
'<html><body class=\'\'>Fred went to Fredmeyer and ran
into <b>Fred</b>.
</body></html>'