php
  • hyperlink
  • relative-path
  • 2012-03-17 104 views 6 likes 
    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'/> 
    

    分别替换。我怎样才能做到这一点?

    回答

    7

    这个代码仅替换链接和图像:

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

    9

    这可以使用来达到的以下内容:

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

    而且

    ../something

    将成为,

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

    但它不会修改“数据:图像/ PN G;”或锚标签。

    我很确定正则表达式可以改进。

    +0

    我喜欢这个!感谢您的写作。巧妙地将preg_replace参数放入键中。我实现了这个功能来完成用户功能请求,以便在我的插件中设置生成Grav网站静态副本的绝对链接。也就是说,如果任何人发现它的问题,我会尝试在这里报告它,以便未来的用户将有一个更好的副本。 – BarryMode 2017-06-18 06:50:53

    1

    你不需要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> 
    

    ,并会将所有文件使用绝对网址

    相关问题