title: php : parse html : extract script tags from body and inject before </body>?
body: <p>I don't care what the library is, but I need a way to extract &lt;.script.> elements from the <strong>&lt;.body.></strong> of a page (as string).  I then want to insert the extracted &lt;.script.>s just before &lt;./body.>.</p>
  
  <p>Ideally, I'd like to extract the &lt;.script.>s into 2 types;<br>
  1) External (those that have the src attribute)
  2) Embedded (those with code between &lt;.script.>&lt;./script.>)</p>
  
  <p>So far I've tried with phpDOM, Simple HTML DOM and Ganon.<br>
  I've had no luck with any of them (I can find links and remove/print them - but fail with scripts every time!).</p>
  
  <p><em>Alternative to<br>
  <a href="https://stackoverflow.com/questions/23414887/php-simple-html-dom-strip-scripts-and-append-to-bottom-of-body">https://stackoverflow.com/questions/23414887/php-simple-html-dom-strip-scripts-and-append-to-bottom-of-body</a></em>
  (Sorry to repost, but it's been 24 Hours of trying and failing, using alternative libs, failing more etc.).</p>
  
  <hr>
  
  <p>Based on the lovely RegEx answer from @alreadycoded.com, I managed to botch together the following;</p>
  
  <pre><code>$output = "&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;&lt;!-- Your stuff --&gt;&lt;/body&gt;&lt;/html&gt;"
  $content = '';
  $js = '';
  
  // 1) Grab &lt;body&gt;
  preg_match_all('#(&lt;body[^&gt;]*&gt;.*?&lt;\/body&gt;)#ims', $output, $body);
  $content = implode('',$body[0]);
  
  // 2) Find &lt;script&gt;s in &lt;body&gt;
  preg_match_all('#&lt;script(.*?)&lt;\/script&gt;#is', $content, $matches);
  foreach ($matches[0] as $value) {
      $js .= '&lt;!-- Moved from [body] --&gt; '.$value;
  }
  
  // 3) Remove &lt;script&gt;s from &lt;body&gt;
  $content2 = preg_replace('#&lt;script(.*?)&lt;\/script&gt;#is', '&lt;!-- Moved to [/body] --&gt;', $content); 
  
  // 4) Add &lt;script&gt;s to bottom of &lt;body&gt;
  $content2 = preg_replace('#&lt;body(.*?)&lt;/body&gt;#is', '&lt;body$1'.$js.'&lt;/body&gt;', $content2);
  
  // 5) Replace &lt;body&gt; with new &lt;body&gt;
  $output = str_replace($content, $content2, $output);
  </code></pre>
  
  <p>Which does the job, and isn't that slow (fraction of a second)</p>
  
  <p>Shame none of the DOM stuff was working (or I wasn't up to wading through naffed objects and manipulating).</p>