试图重写网址。这段代码是否正确?

时间:2013-07-02 12:36:35

标签: php url-rewriting

<?php

include('simple_html_dom.php');
function curPageURL() {
    $pageURL = 'http';
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .=    $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
    }else {
         $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    }
    return $pageURL;
}

// Retrieve the DOM from a given URL
$html = file_get_html(curPageURL());
str_ireplace("http://martianguy.com","http://new.martianguy.com", $html);

?>

我正在尝试用new.martianguy.com(所有href和scr属性)替换域martianguy.com的所有链接。在file_get_html函数中使用当前页面url是否可以?当我在我的本地主机上测试它时,它没有做任何事情,并在30秒后超时。

3 个答案:

答案 0 :(得分:2)

file_get_html()返回一个DOM对象(http://simplehtmldom.sourceforge.net/manual_api.htm),而str_ireplace则需要一个字符串(http://www.php.net/manual/en/function.str-ireplace.php)。

您必须遍历DOM对象并为每个节点执行替换。 您也可以使用file_get_contents(http://php.net/manual/en/function.file-get-contents.php)并替换每个url的出现,但在这种情况下,它不仅仅是src和href。

答案 1 :(得分:1)

对我来说这个脚本是递归的。如果curPageUrl()返回当前页面/脚本的URL,并且调用curPageUrl()的脚本在同一页面上,脚本是否会通过http调用自身?如果是这种情况,它会解释30秒后的超时。该脚本通过http递归调用自身,直到您第一次调用php max_execution_time,默认为30秒。

一些建议:

  1. 如果脚本必须在此页面上,请在curPageUrl()中的URL中添加一个get变量,如果未设置该变量,则只运行替换代码:

    if($_REQUEST['loaded'] != 1) {
        $html = file_get_contents(curPageURL()."?loaded=1");
        echo str_ireplace("oldURL","newURL", $html);
    }
    
  2. 使用javascript,在加载html后在页面上运行,并在客户端进行替换。

  3. 这假设您尝试替换的内容是动态的。如果它是静态的,我会将其保存到文件中,然后使用另一个脚本进行替换。

  4. 希望有所帮助!

答案 2 :(得分:0)

str_ireplace函数不会就地更改字符串。您需要将该函数的输出分配给变量。