title: Formatting HTML code to be output in plain text, with PHP
body: <p>I have this function that takes some user-submitted HTML code from the database:</p>
  
  <pre><code>function Code($code)
  {
      return "&lt;pre&gt;&lt;code&gt;".nl2br(htmlspecialchars($code))."&lt;/code&gt;&lt;/pre&gt;";
  }
  </code></pre>
  
  <p>I'll just be calling it like <code>echo code($query-&gt;row('html'));</code>. I know my question lacks 'depth', but is this the best way to do it? Or could the outputted formatting be parsed (e.g. Javascript injections), or not output correctly on some machines, etc.?</p>
  
  <p>Thanks!</p>
  
  <p>Jack</p>
  
  <p><strong>EDIT: I have a new (related) question</strong>: I would like to highlight the string using <code>highlight_string()</code>. However, I cannot make it work properly. I <em>think</em> I understand why but am not too sure how I can rectify this.</p>
  
  <pre><code>function Code($code)
  {
      return "&lt;pre&gt;&lt;code&gt;".highlight_string(nl2br(htmlspecialchars($code)))."&lt;/code&gt;&lt;/pre&gt;";
  }
  </code></pre>
  
  <p>As you can see from that I'm using <code>highlight_string()</code> on it all. however, the output isn't highlighted at all, instead it is output as character entities (<code>&amp;lt;</code>, '&gt;' etc). If I reshuffle the function ordering to something like:</p>
  
  <p><code>return "&lt;pre&gt;&lt;code&gt;".nl2br(htmlspecialchars(highlight_string($code)))."&lt;/code&gt;&lt;/pre&gt;";</code></p>
  
  <p>I find that the character entities aren't output, but the string still isn't highlighted. To clarify, I have no CSS formatting that would affect the text colour applied either. Also, I've checked my PHP settings and there are definitely highlighting colours specified in there.</p>