What I want to do is to allow users to post code if they need to, so it is viewable and it doesn’t render. For example:
<span>
<div id="hkhsdfhu"></div>
</span>
<h1>Hello</h1>
Should be turned into:
<span>
<div id="hkhsdfhu"></div>
</span>
<h1>Hello</h1>
Only if it is wrapped in <code></code> tags. Right now I am using the following function to allow only certain HTML tags and escape any other tags:
function allowedHtml($str) {
$allowed_tags = array("b", "strong", "i", "em");
$sans_tags = str_replace(array("<", ">"), array("<",">"), $str);
$regex = sprintf("~<(/)?(%s)>~", implode("|",$allowed_tags));
$with_allowed = preg_replace($regex, "<\\1\\2>", $sans_tags);
return $with_allowed;
}
However, if a user wraps their code in <code></code> tags and it contains any of the allowed tags in my function above, those tags will render instead of being escaped. How can I make it where anything in <code></code> tags gets escaped (or just the < and > turned into < and >)? I know about htmlentities() but I don’t want to do that to the whole post, only stuff inside <code></code> tags.
Thanks in advance!
Just use a single
preg_replace()function with the e modifier to execute anhtmlenteties()function on everything it finds within<code>tagsEDITED
Rewrote your
allowedHtml()function and added astr_replace()at the end.It’s tested and should now work perfectly 🙂
UPDATED – NEW SOLUTION
Discussed another solution, and the above code will fix that. It works just like the Stack Overflow html conversion, which means that ** becomes bold, * becomes italic, _ becomes underlined and – is “strikethrough”. On top of that, all lines starting with 4 or more spaces will be output as code