PHP: Find images and links with relative path in output and convert them to absolute path
absolute-path, image, php, relative-path, src
Solution
After some further research I've stumbled upon this article from Gerd Riesselmann on how to solve the absence of a `base href` solution for RSS-feeds. His snippet actually solves my question!
http://www.gerd-riesselmann.net/archives/2005/11/rss-doesnt-know-a-base-url
<?php
function relToAbs($text, $base)
{
if (empty($base))
return $text;
// base url needs trailing /
if (substr($base, -1, 1) != "/")
$base .= "/";
// Replace links
$pattern = "/<a([^>]*) " .
"href=\"[^http|ftp|https|mailto]([^\"]*)\"/";
$replace = "<a\${1} href=\"" . $base . "\${2}\"";
$text = preg_replace($pattern, $replace, $text);
// Replace images
$pattern = "/<img([^>]*) " .
"src=\"[^http|ftp|https]([^\"]*)\"/";
$replace = "<img\${1} src=\"" . $base . "\${2}\"";
$text = preg_replace($pattern, $replace, $text);
// Done
return $text;
}
?>
Thank you Gerd! And thank you shadyyx to point me in the direction of `base href`!
Problem
There are a lot of posts on converting relative to absolute paths in PHP. I'm looking for a specific implementation beyond these posts (hopefully). Could anyone please help me with this specific implementation? I have a PHP variable containing diverse HTML, including `href`s and `img`s containing relative urls. Mostly (for example) `/en/discover` or `/img/icons/facebook.png` I want to process this PHP variable in such a way that the values of my `href`s and `img`s will be converted to `http://mydomain.com/en/discover` and `http://mydomain.com/img/icons/facebook.png` I believe the question below covers the solution for `href`s. How can we expand this to also consider `img`s? - Change a relative URL to absolute URL Would a regex be in order? Or since we're dealing with a lot of output should we use DOMDocument?