preg_replace change link from href

老子叫甜甜 提交于 2019-12-03 21:41:47

Remove this unnecessary part from your regexps: ([^/]+)/

It causes your regular expressions to match all the way to the url in the next tag.

Code:

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

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>

But! I think what you really want is a way to replace relative urls with absolute urls. For that you can use these regexp (with this you can skip the if-checks):

$result = preg_replace('/src="(?!http:\/\/)([^"]+)"/', "src=\"http://google.com/\\1\"", $result);
$result = preg_replace('/href="(?!http:\/\/)([^"]+)"/', "href=\"http://google.com/\\1\"", $result);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!