【问题标题】:preg_replace change link from hrefpreg_replace 从 href 更改链接
【发布时间】:2013-10-11 23:32:06
【问题描述】:

我需要替换 curl 获取的页面中的 url 并添加正确的图像和链接链接。我的 php curl 代码是:

<?php

$result = '<a href="http://host.org"><img src="./sec.png"></a>
<link href="./styles.css" rel="alternate stylesheet" type="text/css" />
<script type="text/javascript" src="./style.js"></script>';

echo $result;
 if (!preg_match('/src="https?:\/\/"/', $result)) {
        $result = preg_replace('/src="(http:\/\/([^\/]+)\/)?([^"]+)"/', "src=\"http://google.com/\\3\"", $result);
    }
echo $result;
if (!preg_match('/href="https?:\/\/"/', $result)) {
        $result = preg_replace('/href="(http:\/\/([^\/]+)\/)?([^"]+)"/', "href=\"http://google.com/\\3\"", $result);
    }
echo $result;

?>

输出是:

//original links
<a href="http://host.org"><img src="./sec.png"></a>
<link href="./styles.css" type="text/css" />
<script src="./style.js"></script><br />

//fixed SRC path
<a href="http://host.org"><img src="http://google.com/./sec.png"></a>
<link href="./styles.css" type="text/css" />
<script src="http://google.com/./style.js"></script>

//fixed HREF path
<a href="http://google.com//google.com/./sec.png"></a>
<link href="http://google.com/./styles.css" type="text/css" />
<script src="http://google.com/./style.js"></script>

但是当链接是“a”时,它会切断所有链接,只留下 href 值。

//from
<a href="http://host.org"><img src="./sec.png"></a>
//to src fix:
<a href="http://host.org"><img src="http://google.com/./sec.png"></a>
//ERRRROR when href fix make :
<a href="http://google.com//google.com/.sec.png"></a>

任何机构都可以帮助解决它。谢谢

【问题讨论】:

    标签: php regex preg-replace preg-match preg-match-all


    【解决方案1】:

    从你的正则表达式中删除这个不必要的部分:([^/]+)/

    它会导致你的正则表达式一直匹配到下一个标签中的 url。

    代码:

    $result = preg_replace('/src="(http:\/\/)?([^"]+)"/', "src=\"http://google.com/\\2\"", $result);
    $result = preg_replace('/href="(http:\/\/)?([^"]+)"/', "href=\"http://google.com/\\2\"", $result);
    

    结果:

    <a href="http://google.com/host.org"><img src="http://google.com/./sec.png"></a> 
    <link href="http://google.com/./styles.css" rel="alternate stylesheet" type="text/css" /> 
    <script type="text/javascript" src="http://google.com/./style.js"></script>
    

    但是!我认为您真正想要的是一种用绝对网址替换相对网址的方法。 为此,您可以使用这些正则表达式(这样您可以跳过 if-checks):

    $result = preg_replace('/src="(?!http:\/\/)([^"]+)"/', "src=\"http://google.com/\\1\"", $result);
    $result = preg_replace('/href="(?!http:\/\/)([^"]+)"/', "href=\"http://google.com/\\1\"", $result);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-02
      • 1970-01-01
      • 2014-03-24
      • 2011-01-13
      • 2015-07-12
      • 2021-09-14
      相关资源
      最近更新 更多