Well, you'll have to make a decision. htmlentites converts all < and > to their html equivalents. If you don't want to do that, remove that call. Then for php tags, just do str_replaces.
ie.
$text = str_replace('<?', '&lt;?', $text);
$text = str_replace('?>', '?&gt;', $text);