将相对链接转化为绝对链接


Make relative links into absolute ones

我正在请求这样一个网站的源代码:

<? $txt = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741');
echo $txt; ?>

但是,我想用绝对链接取代相对链接!基本上,

<img src="/images/legend_15s.png"/> and <img src='/images/legend_15s.png'/>

应该被取代

<img src="http://domain.com/images/legend_15s.png"/> 

<img src='http://domain.com/images/legend_15s.png'/>

分别。我该怎么做?

这可以通过以下方法实现:

<?php 
$input = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741');
$domain = 'http://stats.pingdom.com/';
$rep['/href="(?!https?:'/'/)(?!data:)(?!#)/'] = 'href="'.$domain;
$rep['/src="(?!https?:'/'/)(?!data:)(?!#)/'] = 'src="'.$domain;
$rep['/@import['n+'s+]"'//'] = '@import "'.$domain;
$rep['/@import['n+'s+]"'./'] = '@import "'.$domain;
$output = preg_replace(
    array_keys($rep),
    array_values($rep),
    $input
);
echo $output;
?>

其输出链接如下:

/

将变成

http://stats.pingdom.com//something

/

将变成

http://stats.pingdom.com/../something

但它不会编辑"data:image/png;"或锚定标记。

不过,我确信正则表达式是可以改进的。

此代码仅替换链接和图像:

<? $txt = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741');
$txt = str_replace(array('href="', 'src="'), array('href="http://stats.pingdom.com/', 'src="http://stats.pingdom.com/'), $txt);
echo $txt; ?>

我已经测试了它的工作:)

更新

这是用正则表达式完成的,并且工作得更好:

<? $txt = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741');
$domain = "http://stats.pingdom.com";
$txt = preg_replace("/(href|src)'='"([^(http)])('/)?/", "$1='"$domain$2", $txt);
echo $txt; ?>

完成:D

您不需要php,只需要使用html5基本标记,并将php代码放在html主体中,只需要执行以下操作示例:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <base href="http://yourdomain.com/">
</head>
<body>
<? $txt = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741');
echo $txt; ?>
</body>
</html>

并且所有文件都将使用绝对url