使用正则表达式更改HTML

时间:2009-12-13 12:24:17

标签: php regex

我如何进行输入html并更改任何转到本地地址的src或href链接(例如href =“index.html”到其完整位置(指定),例如href =“http:// www。 somesite.com/index.html“)这是一个从另一个站点获取文件并显示它的网站(有点像代理)

3 个答案:

答案 0 :(得分:5)

查看<base>标记。它允许您定义所有链接相对的位置。

答案 1 :(得分:1)

如果您对不一定严格的随机HTML页面执行此操作,正则表达式对您来说将是一件非常令人头疼的问题,因为您必须处理非标准属性,例如:

href="some_url"
href='some_url'
href=some_url

我的建议是使用DOM函数执行此任务。你可以在这些行中做一些事情(未经测试):

$doc = new DOMDocument();
@$doc->loadHTMLFile($url); // suppress warnings about html errors
$xpath = new DOMXpath($doc);
$hrefs = $xpath->query("//*[@href]/@href"); // select the href attribute of all elements that have a href attribute
for ($i=0; $i < $hrefs->length; $i++) {
    $href = $hrefs->item($i);
    $href->nodeValue = make_new_url($href->nodeValue); // this is where the magic happens
}
// now do the same for src attributes

同样,这段代码可能需要一些调整,特别是XPath查询,不太确定。

对于手头的任务来说,使用DOM扩展可能看起来过于复杂,但它也可以为你完成这项任务和未来任务带来很多麻烦和时间。

答案 2 :(得分:-1)

**你不需要任何正则表达式来解决这个问题, ** $_SERVER['HTTP_HOST']

$cur_dir = basename(dirname($_SERVER['PHP_SELF']));
$host = $_SERVER['HTTP_HOST'];
echo $host."/".$cur_dir."/"$filename;

这将打印http://www.yourdomain.blabla/your/images/index.html