title: PHP - Inject script into the <head>
body: <p>Run into a bit of a sticky situation which I can't seem to wrap my finger around. Basically what I am trying to achieve is having the ability to inject different Javascript files on different page.</p>
  
  <p>Some simple, random example:</p>
  
  <ul>
  <li>Page 1: import <strong>jquery.js</strong></li>
  <li>Page 2: import <strong>mootools.js</strong></li>
  </ul>
  
  <p>So what I have done is, I've created a function called <code>addScript()</code> like so:</p>
  
  <pre><code>function addScript($file) {
  
      $script = '';
      $script .= '&lt;script src="'. REL_PATH . '/path/to/file/' . $file . '"&gt;';
      $script .= '&lt;/script&gt;';
  
      return $script;
  }
  </code></pre>
  
  <p>so if I call <code>addScript('jquery.min');</code> it, outputs correctly.</p>
  
  <p>What I now want to do is replace the closing <code>&lt;/head&gt;</code> tag with the output from the above function. If I do the following then it works fine:</p>
  
  <pre><code>ob_start();
  require_once("models/header.php");
  $contents = ob_get_contents();
  ob_end_clean();
  
  echo str_replace('&lt;/head&gt;', addScript('jquery.js') . '&lt;/head&gt;', $contents);
  </code></pre>
  
  <p>However I would like this to be a little more dynamic as there may be multiple script that I need to inject on each page like so:</p>
  
  <pre><code>addScript('script.js');
  addScript('script2.js');
  addScript('script3.js');
  </code></pre>
  
  <p>I then thought of creating a <code>getHead()</code> function with a foreach loop inside and returning <code>str_replace</code> there instead but this did not work.</p>
  
  <p>Can anyone guide my in the direction to dynamically inject as many script as required and output the last bit of the head?</p>