Chr*_*ede 6 php relative-path hyperlink
我正在请求这样的网站的源代码:
<? $txt = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741');
echo $txt; ?>
Run Code Online (Sandbox Code Playgroud)
我想用绝对的替换相关链接!基本上,
<img src="/images/legend_15s.png"/> and <img src='/images/legend_15s.png'/>
Run Code Online (Sandbox Code Playgroud)
应该被替换
<img src="http://domain.com/images/legend_15s.png"/>
Run Code Online (Sandbox Code Playgroud)
和
<img src='http://domain.com/images/legend_15s.png'/>
Run Code Online (Sandbox Code Playgroud)
分别.我怎样才能做到这一点?
pac*_*nka 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;
?>
Run Code Online (Sandbox Code Playgroud)
哪个输出链接如下:
/东西
会变成,
和
../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; ?>
Run Code Online (Sandbox Code Playgroud)
我测试过它的工作:)
更新
这是通过正则表达式完成并更好地工作:
<? $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; ?>
Run Code Online (Sandbox Code Playgroud)
完成:D