Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I escape all code within <code></code> tags to allow people to post code?
    primarykey
    data
    text
    <p>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:</p> <pre><code>&lt;span&gt; &lt;div id="hkhsdfhu"&gt;&lt;/div&gt; &lt;/span&gt; &lt;h1&gt;Hello&lt;/h1&gt; </code></pre> <p>Should be turned into:</p> <pre><code>&amp;lt;span&amp;gt; &amp;lt;div id="hkhsdfhu"&amp;gt;&amp;lt;/div&amp;gt; &amp;lt;/span&amp;gt; &amp;lt;h1&amp;gt;Hello&amp;lt;/h1&amp;gt; </code></pre> <p>Only if it is wrapped in <code>&lt;code&gt;&lt;/code&gt;</code> tags. Right now I am using the following function to allow only certain HTML tags and escape any other tags:</p> <pre><code>function allowedHtml($str) { $allowed_tags = array("b", "strong", "i", "em"); $sans_tags = str_replace(array("&lt;", "&gt;"), array("&amp;lt;","&amp;gt;"), $str); $regex = sprintf("~&amp;lt;(/)?(%s)&amp;gt;~", implode("|",$allowed_tags)); $with_allowed = preg_replace($regex, "&lt;\\1\\2&gt;", $sans_tags); return $with_allowed; } </code></pre> <p>However, if a user wraps their code in <code>&lt;code&gt;&lt;/code&gt;</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>&lt;code&gt;&lt;/code&gt;</code> tags gets escaped (or just the <code>&lt;</code> and <code>&gt;</code> turned into <code>&amp;lt;</code> and <code>&amp;gt;</code>)? I know about <code>htmlentities()</code> but I don't want to do that to the whole post, only stuff inside <code>&lt;code&gt;&lt;/code&gt;</code> tags.</p> <p>Thanks in advance! </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload