小编Eug*_*nia的帖子

preg_replace更改来自href的链接

我需要替换curl拍摄的页面中的网址,并向图像和链接添加正确的链接。我的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;

?>
Run Code Online (Sandbox Code Playgroud)

输出为:

//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> …
Run Code Online (Sandbox Code Playgroud)

php regex preg-replace preg-match-all preg-match

1
推荐指数
1
解决办法
5622
查看次数

标签 统计

php ×1

preg-match ×1

preg-match-all ×1

preg-replace ×1

regex ×1