title: replace all but certain html tags with htmlspecialchars() in PHP?
body: <p>I would like to process my user input to allow only certain html tags, and replace the other ones by their html entities, as well as replace non-tag-characters. For example, if I only wanted to allow the <code>&lt;b&gt;</code> and the <code>&lt;a&gt;</code> tag, then </p>
  
  <pre><code>allow_only("This is &lt;b&gt;bold&lt;/b&gt; and this is &lt;i&gt;italic&lt;/i&gt;.
              Moreover 2&lt;3 and &lt;a href='google.com'&gt;this is a link&lt;/a&gt;.","&lt;b&gt;&lt;a&gt;");
  </code></pre>
  
  <p>should produce </p>
  
  <pre><code>This is &lt;b&gt;bold&lt;/b&gt; and this is &amp;lt;i&amp;gt;italic&amp;lt;/i&amp;gt;.
  Moreover 2&amp;lt;3 and &lt;a href='google.com'&gt;this is a link&lt;/a&gt;.
  </code></pre>
  
  <p>How can I do this in PHP? I am aware of <code>strip_tags()</code> that can <strong>remove</strong> the unwanted tags completely, and I'm aware of <code>htmlspecialchars()</code> which can replace <strong>all tags</strong> by their html entities, but none where only specific tags get replaced. How can this be done in PHP?</p>
  
  <p>And if there is no 'common' way to do this, how should I in general go on processing user input that can have valid regular html, but can also have <code>&lt;</code> signs and potentially dangerous html code?</p>