title: PHP DOM - Parse text nodes that contain certain HTML tags
body: <p>I recently received help in parsing all text nodes from an HTML document.  The resulting code was this:</p>
  
  <pre><code>$doc = new DOMDocument();
  $doc-&gt;loadHTML($contents);
  $doc-&gt;loadHTML("&lt;p&gt;not in the brackets..&lt;/p&gt;");
  $xpath = new DOMXPath($doc);
  $textnodes = $xpath-&gt;evaluate('//text()');
  </code></pre>
  
  <p>Using the following extract:</p>
  
  <pre><code>&lt;p&gt;This is a &lt;b&gt;nested &lt;i&gt;HTML&lt;/i&gt; tag&lt;b&gt;...&lt;/p&gt;
  </code></pre>
  
  <p>I am able to create an array of elements:</p>
  
  <pre><code>Array
  (
    [0] =&gt; This is a 
    [1] =&gt; nested
    [2] =&gt; HTML
    [3] =&gt; tag
    [4] =&gt; ...
  )
  </code></pre>
  
  <p>What I would actually like to do, though, is to retrieve all text nodes <strong>but to allow certain HTML tags to be 'looked over'</strong>.  For instance, I do not want <code>&lt;i&gt;</code>, <code>&lt;b&gt;</code> and <code>&lt;u&gt;</code> tags to be parsed as individual nodes; I would rather they are joined on to the previous text node.  The above array would, ideally, look like this:</p>
  
  <pre><code>Array
  (
    [0] =&gt; This is a nested HTML tag...
  )
  </code></pre>
  
  <p>On the other hand, the <code>&lt;p&gt;</code> tags <em>should</em> be recognised as separate nodes.  So the following text:</p>
  
  <pre><code>&lt;p&gt;paragraph 1 &lt;b&gt;here&lt;/b&gt;&lt;/p&gt; &lt;p&gt;paragraph 2&lt;/b&gt;
  </code></pre>
  
  <p>Would ideally be parsed as:</p>
  
  <pre><code>Array
  (
    [0] =&gt; paragraph 1 &lt;b&gt;here&lt;/b&gt;
    [1] =&gt; paragraph 2
  </code></pre>
  
  <p>I have done some reading about XPath and the PHP DOM, but honestly, I don't really have a clue how to go about this.  Can anybody point me in the right direction?  Thank you.</p>
  
  <p><strong>Edit</strong></p>
  
  <p>Just to clarify the output must be in array format; my aim is to parse all text from a page so it can then be used in a translation file.  Certain HTML tags (<code>&lt;b&gt;</code>, etc) are therefore desirable in the parsed text in order to keep full sentences together - and to keep the markup roughly intact - in the new translation file.</p>