替换除CSS和js以外的所有链接的正则表达式


regular expression for replacing all links but css and js

我想下载一个网站,并将该网站上的所有链接替换为内部链接。

这很简单:

$page=file_get_contents($url);
$local=$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
$page=preg_replace('/href="(.+?)"/','href="http://'.$local.'?href=''1"',$page);

,但我想排除所有的CSS文件和js文件从替换,所以我尝试:

$regex='/href="(.+?(?!('.js|'.css)))"/';
$page=preg_replace($regex,'href="http://'.$local.'?href=''1"',$page);

但这不起作用,

我做错了什么?

i thought

?!

是一个负数

要回答您的regex问题,您需要查看后面的内容,并使用字符类更好地限制匹配:

$regex = '/href="([^"]+(?<!'.js|'.css))"/';

charclass首先匹配整个链接内容,然后断言它不以.js.css结束。你甚至可能想用<a's[^>]*?来增加整个匹配,所以它真的只是找到任何看起来像链接的东西。

另一种选择是使用domdocument或querypath来完成这样的任务,这通常是冗长且更多的代码,但更简单的是添加编程条件:

htmlqp->find("a") FOREACH $a->attr("href", "http:/...".$a->attr("href"))
// would need a real foreach and an if and stuff..