title: Getting Text Between HTML Tags & Replacing Them
body: <p>I would like to get text between HTML tags and replacing them dynamically. Considering HTML tags might contain anything (nested HTML tags, comments, etc) I think <a href="http://www.php.net/manual/en/class.domdocument.php" rel="nofollow">DOM Document</a> class is the way to go. However I wasn't able to find any example for my needs. I can only get the text between of specifically selected html tag. I also couldn't find an example to replace selected text.</p>
  
  <pre><code>&lt;?php 
  // HTML OUTPUT
  $html= "&lt;p&gt;Subject,&lt;/p&gt;
  &lt;h1&gt;H1 title&lt;/h1&gt;
  &lt;h2&gt;H2 title&lt;/h2&gt;
  &lt;h3&gt;H2 title&lt;/h3&gt;";
  
  // DESIRED OUTPUT
  $newHTML "&lt;p&gt;My Fav. Colors;&lt;/p&gt;
  &lt;h1&gt;Blue&lt;/h1&gt;
  &lt;h2&gt;Orange&lt;/h2&gt;
  &lt;h3&gt;Yellow&lt;/h3&gt;";
  ?&gt;
  </code></pre>
  
  <p>Basically I would like to get text from HTML output dynamically (might contain nested HTML tags, comments, javascripts scripts and so on.) and replace them (replaced values will be selected from database) to create new HTML output.</p>
  
  <p>What is the best and elegant way to go? Is <a href="http://www.php.net/manual/en/class.domdocument.php" rel="nofollow"><strong>DOM Document</strong></a> class is the tool I need or <strong>Regex</strong> is the way to go?</p>
  
  <p>I will be really glad if you could show me with a small piece of code to understand it clearly.</p>
  
  <p><strong>P.S.</strong> HTML document in question might be a page on another domain. Such as <a href="http://anotherdomain.com/page.html" rel="nofollow">http://anotherdomain.com/page.html</a>.</p>