- htmlentities: documentation ( source)
- preg_replace: documentation ( source)
<?php
$pattern = '/\[CODE\](.*)\[\/CODE\]/';
$replacement = function($m) { return htmlentities($m[0]); };
$subject = <<<EOT
<html>
<body>
<div id="box1">[CODE]<span class="test">Hello World</span>[/CODE]</div>
<div id="box2">[CODE]<strong class="test2">Nice to meet you!</strong>[/CODE]</div>
</body>
</html>
EOT;
echo preg_replace($pattern, $replacement, $subject);