Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode HTML entities but ignore HTML tags - in PHP

I have a string that might look like this

$str = "<p>Me & Mrs Jones <br /> live in <strong style="color:#FFF;">España</strong></p>";
htmlentities($str,ENT_COMPAT,'UTF-8',false);

How can I convert the text to HTML entities without converting the HTML tags?

note: I need to keep the HTML intact

like image 808
ed209 Avatar asked Dec 22 '09 12:12

ed209


Video Answer


2 Answers

Disclaimer: I would not encode any entities, except for <, > and &. That said, if you really want this, do this:

$str = '...';
$str = htmlentities($str,ENT_NOQUOTES,'UTF-8',false);
$str = str_replace(array('&lt;','&gt;'),array('<','>'), $str);
like image 168
Evert Avatar answered Sep 28 '22 16:09

Evert


The problem, that you face, is that under circumstances you already have encoded '<' and '>' in your text, so you have to filter them out after conversion.

This is similar to Evert's answer, but adds one more step to allow for content like 1 < 2 in your markup:

$str = htmlentities($str,ENT_NOQUOTES,'UTF-8',false);
$str = str_replace(array('&lt;','&gt;'),array('<','>'), $str);
$str = str_replace(array('&amp;lt;','&amp;gt'),array('&lt;','&gt;'), $str);
like image 40
Boldewyn Avatar answered Sep 28 '22 15:09

Boldewyn