繁体   English   中英

preg_replace更改来自href的链接

[英]preg_replace change link from href

我需要替换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>

任何身体都可以帮助修复它。 谢谢

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

它使您的正则表达式始终与下一个标记中的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>

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM