将相对链接转换为绝对链接。

6

我想要获取一个类似于这样的网站的源代码:

<? $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'/>

分别。我该怎么做?
3个回答

10

可以通过以下方式实现:

<?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;
?>

以下代码将会输出以下链接:

/something

将变成:

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

../something

将变成:

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

但是它不会编辑"data:image/png;"或锚点标签。

我相信正则表达式可以进一步改进。


我喜欢这个!谢谢你写了它。将 preg_replace 参数放入键中是聪明的做法。我实现了这个功能,以满足用户要求在我的插件中设置 Grav 网站静态副本的绝对链接。话虽如此,如果有人发现问题,我会尽力在这里报告,以便未来的用户能够获得更好的副本。 - Barry

9

这段代码仅替换链接和图片:

<? $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


0
你不需要 PHP,只需要使用 HTML5 的基础标签,并将你的 PHP 代码放在 HTML body 中,你只需要按照以下步骤操作: 例如:

<!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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接