对于一个项目,我需要获取一个网站的内容,并改变HTML代码。该网站上的每个链接都必须替换为我自己的链接。我一直使用str_replace,直到我意识到链接有时会被分配类。
我已经尝试过在<a> </a>标签之间的每个href链接之前添加我自己的网站的preg_replace函数。在$content中获取的网站是否包含href=""或href=''应该无关紧要。
$content = preg_replace('~(<a\b[^>]*\shref=")([^"]*)(")~igs', '\1http://website.com/fetch.php?url=\2\3', $content);这不起作用,我找不到错误。其行为应如下所示:
<a class="link" href="http://google.com">Google</a>应该变成
<a class="link" href="http://website.com/fetch.php?url=http://google.com">Google</a>有人能帮我找出错误吗?提前谢谢你。
发布于 2016-11-03 11:48:30
不要半途而废一个会漏掉很多案例的正则表达式。只需将每个文档读入到DOM树中(尝试使用此html5 DOM parser ),然后使用XPath获取具有href属性的所有链接,并更新它们,然后保存结果。
发布于 2016-11-03 12:14:36
只需使用simplexml和preg_replace即可
<?php
$string= '<a class="link" href="http://google.com">Google</a>';
$a = new SimpleXMLElement('<a class="link" href="http://google.com">Google</a>');
$newurl="http://website.com/fetch.php?url=".urlencode($a['href']);
$pattern = "/(?<=href=(\"|'))[^\"']+(?=(\"|'))/";
$body = preg_replace($pattern,$newurl,$string);
echo $body;
?>输出:
<a class="link" href="http://website.com/fetch.php?url=http%3A%2F%2Fgoogle.com">Google</a>https://stackoverflow.com/questions/40324935
复制相似问题