【问题标题】:Make relative links into absolute ones将相对链接变成绝对链接
【发布时间】:2012-04-02 21:04:24
【问题描述】:

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

<? $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 hyperlink relative-path


    【解决方案1】:

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

    <?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;”或锚标记。

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

    【讨论】:

    • 我喜欢这个!谢谢你写它。巧妙地将 preg_replace 参数放入键中。我实现了这个来满足用户功能请求,在我的插件中设置绝对链接,生成 Grav 网站的静态副本。也就是说,如果有人发现它有问题,我会尝试在这里报告它,以便未来的用户可以获得更好的副本。
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      你不需要php,你只需要使用html5 base标签,并将你的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

      【讨论】:

        猜你喜欢
        • 2010-10-07
        • 2010-09-25
        • 2015-12-04
        • 2015-01-13
        • 1970-01-01
        • 2013-10-10
        • 2019-04-04
        • 1970-01-01
        • 2011-02-21
        相关资源
        最近更新 更多