Question

It would be nice if I could call my_escape($text, '<p><b><i>') that escapes everything except all <p>, <b> and <i> tags. I'm looking for a generic solution where I can specify an arbitrary set of tags. Does this exist? If not what's the best approach to implement it?

Was it helpful?

Solution

in htmlspecialchars function it converts html tags to

& to &amp;
" to &quot;
' to &#039;
< to &lt;
> to &gt;

after convert you can do reverse to decode

<?php
$test="<p><b><a>Test</b></a></p>";

$test = htmlspecialchars($test);

$test = str_replace("&lt;p&gt;", "<p>", $test);
$test = str_replace("&lt;i&gt;", "<i>", $test);
$test = str_replace("&lt;b&gt;", "<b>", $test);
$test = str_replace("&lt;/b&gt;", "</b>", $test);
$test = str_replace("&lt;/i&gt;", "</i>", $test);
$test = str_replace("&lt;/p&gt;", "</p>", $test);

echo $test;
?>

OTHER TIPS

Your best bet is to do something like this

// Add placeholders
$search = array('<p>', '<b>');
$replace = array("\ap\a", "\ab\a");
$text = str_replace($search, $replace, $text);

$text = htmlspecialchars($text);

// Put it all back together
$text = str_replace($replace, $search, $text);

It would be best to use a regular expression, but that is a lot more explaining.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top