title: PHP RegEx: Replace all relative paths in HTML-string, with absolute paths
body: <p>I'm working on a project where I need to scrape some content from the same site, but a subfolder, and store it. I know it's not  ideal, but it's sadly the best approach for the client.</p>
  
  <p><strong>I need to change all references from relative to absolute URLs</strong><br>
  All the references (images, css, js) are referred relatively with both:</p>
  
  <ul>
  <li>"../../imgs/"</li>
  <li>"/js/"</li>
  </ul>
  
  <p>... which means they don't work in my sub-folder. I need a function that matches the regex on these references and replaces the path.</p>
  
  <p>When I try this:</p>
  
  <pre><code>function getRelativeContent($url) {
      $page = file_get_contents($url);
  
      //url needs trailing /
      if (substr($url, -1, 1) != "/")
          $url .= "/";
  
      $page = preg_replace('/src="(\/)?([\w_\-\/\.\?&amp;=@%#]*)"/i','src="' . $url . '$2"', $page);
      $page = preg_replace('/href="(\/)?([\w_\-\/\.\?&amp;=@%#]*)"/i','href="' . $url . '$2"', $page);
  
      return $page;
  }
  
  echo getRelativeContent($url);
  </code></pre>
  
  <p>Then these URLs doesn't work: </p>
  
  <pre><code>&lt;link href="/cassette.axd/stylesheet/fdbdaa59cb97b35f06f65fd41cb60caa3975cc0f/forbrug-rwd_(max-width 767px)" type="text/css" rel="stylesheet" media="(max-width: 767px)"&gt;
  
  &lt;img src="https://www.domain.dk/~/media/2561BD6AFBD64402877E4ACED01F97FD.ashx" /&gt;
  </code></pre>