title: How to identify if a text is HTML or not? (in PHP)
body: <p>I want to read text entries from a database, some of which are actually HTML entries, others are just plain text that might contain HTML markup which should be displayed as text.</p>
  
  <p>Those that are plain text should then be converted to HTML, by first calling PHP's <code>htmlspecialchars()</code> function and then running the result through HTMLPurifier.</p>
  
  <p>Or in other words, I'm looking for some tips on how to implement the isHTML() function:</p>
  
  <pre><code>$text = getTextFromDatabase();
  if (!isHTML($text)) {
      $text = htmlspecialchars($text);
  }
  $purifier = new HTMLPurifier();
  $clean_html = $purifier-&gt;purify($text);
  </code></pre>
  
  <p>So for example following text would be run through <code>htmlspecialchars</code>:</p>
  
  <pre><code>The &lt;p&gt; tag of HTML has to be followed by a &lt;/p&gt; tag to end the paragraph.
  </code></pre>
  
  <p>And following text would not be run through <code>htmlspecialchars</code>:</p>
  
  <pre><code>&lt;p&gt;These are few lines of HTML.&lt;/p&gt;
  &lt;div&gt;There might be multiple independent&lt;/div&gt;
  &lt;p&gt;but valid HTML blocks in it.&lt;/p&gt;
  </code></pre>
  
  <p>It seems like there should already be an <code>isHTML()</code> function out there, but I just can't happen to find it and I don't want to reinvent the wheel :-). Maybe it's even possible to do this with some kind of HTMLPurifier settings?</p>
  
  <p>Note that, if the HTML code is buggy, this should be handled by HTMLPurifier and the code should not be run through <code>htmlspecialchars</code>. :-) Like for example having an opening <code>&lt;p&gt;</code> tag when there really should be a closing <code>&lt;/p&gt;</code> tag in the HTML code.</p>
  
  <p>Any help is appreciated, thanks already :-),<br>
  Robert.</p>