更快的方法来替换特定的图像链接XPath / Preg_replace

时间:2015-01-24 10:17:20

标签: php dom xpath getattribute

我编写了一小段加载HTML内容的代码。处理每个图像并检查它是否具有完整的URL集。

如果没有,则添加它。

目前我正在使用XPath。 但我觉得这个程序会占用大量CPU资源。 因此,我想知道我目前所做的事情是否会有更快的方法。

我写的代码

        ///######## START A NEW DOM DOCUMENT
        $dom            = new DOMDocument;
        ///######## LOAD THE HTML INTO THE DOM DOCUMENT
        $dom->loadHTML($html);
        ///######## GET ALL IMAGES WITH XPath
        $Images         = $dom->getElementsByTagName('img');
        ///######## SETUP AN EMPTY SOURCE AND TARGET ARRAY
        $SourceArray    = $TargetArray = array();

        ///######## RUN THROUGH ALL SET IMAGE NODES
        foreach ($Images as $node) {
            ///######## GET THE URL ATTRIBUTE
            $SetURL = $node->getAttribute('src').PHP_EOL;

            ///######## IF THE URL DOES NOT START WITH HTTP
            if(substr($SetURL, 0, 4) != 'http'){
                ///######## SET THE URL TO THE SOURCE ARRAY
                $SourceArray[] = 'img src="'.$SetURL;
                ///######## SET THE TARGET URL
                $TargetArray[] = 'img src="'.__APPBASE__.'/'.$this->TEMPLATEDIR.'/'.$SetURL;
            }
        }
        ///######## REMOVE THE BREAKS FROM BOTH ARRAYS
        $SourceArray    = str_replace(PHP_EOL, NULL, $SourceArray);
        $TargetArray    = str_replace(PHP_EOL, NULL, $TargetArray);
        ///######## REPLACE THE HTML TEXT
        $html           = str_replace($SourceArray, $TargetArray, $html);

        ///######## UNSET THE VARIABLES {free up memory}
        unset($dom);
        unset($SourceArray);
        unset($TargetArray);

0 个答案:

没有答案