貪欲な量指定子を活用し、1 つの高度な手法を使用します。
~.*\K</body>~s
いくつかの説明:
~ # A simple delimiter
.* # Match anything greedy (until the end)
\K # Forget what we matched until now
</body> # Match ¨</body>¨
~ # The closing delimiter
s # The s modifier to also match newlines with the dot ¨.¨
PHP の実装は次のようになります。
$str = '
</body>
Something !
</body>
</body>
</body>
</body>
</html>';
$search = '</body>';
$replace = '</replaced>';
$str = preg_replace('~.*\K'. preg_quote($search, '~') . '~s', '$1' . $replace, $str);
echo $str;
preg_quote()
信頼できないユーザーから使用される可能性のある適切な文字をエスケープしていたことに注意してください。
出力:
</body>
Something !
</body>
</body>
</body>
</replaced>
</html>