En
http://ar2.php.net/manual/es/function.htmlentities.php en los comentarios está la respuesta exacta a tu pregunta
Código PHP:
//a function to encode everything but html tags. pattern improvement is much appreciated!
function htmlEncodeText ($string)
{
$pattern = '<([a-zA-Z0-9\. "\'_\/-=;\(\)?&#%]+)>';
preg_match_all ('/' . $pattern . '/', $string, $tagMatches, PREG_SET_ORDER);
$textMatches = preg_split ('/' . $pattern . '/', $string);
foreach ($textMatches as $key => $value) {
$textMatches [$key] = htmlentities ($value);
}
for ($i = 0; $i < count ($textMatches); $i ++) {
$textMatches [$i] = $textMatches [$i] . $tagMatches [$i] [0];
}
return implode ($textMatches);
}