使用regex或DOMDocument替换最后一个字符(字符串)


Replacing last char (string) using regex or DOMDocument

我使用一个小脚本从绝对链接转换为相对链接。它正在发挥作用,但需要改进。不知道如何继续。请看一下这部分脚本。

脚本:

public function links($path) {
    $old_url = 'http://test.dev/'; 
    $dir_handle = opendir($path);
    while($item = readdir($dir_handle)) {
        $new_path = $path."/".$item;
        if(is_dir($new_path) && $item != '.' && $item != '..') {
            $this->links($new_path);
        }
        // it is a file
        else{
            if($item != '.' && $item != '..')
            {
                $new_url = '';
                $depth_count = 1;
                $folder_depth = substr_count($new_path, '/');
                while($depth_count < $folder_depth){
                    $new_url .= '../';
                    $depth_count++;

                }
                $file_contents = file_get_contents($new_path);
                $doc = new DOMDocument;
                @$doc->loadHTML($file_contents);
                foreach ($doc->getElementsByTagName('a') as $link) {
                        if (substr($link, -1) == "/"){
                            $link->setAttribute('href', $link->getAttribute('href').'/index.html');
                        }
                    }
                $doc->saveHTML();
                $file_contents = str_replace($old_url,$new_url,$file_contents);
                file_put_contents($new_path,$file_contents);
            }
        }
    }
}

正如你所看到的,我已经在while loop中添加了DOMDocument,但它不起作用。这里我要做的是在每个链接末尾添加index。html如果链接的最后一个字符是/

我做错了什么?

谢谢。

这是你想要的吗?

$file_contents = file_get_contents($new_path);
$dom = new DOMDocument();
$dom->loadHTML($file_contents);
$xpath = new DOMXPath($dom);
$links = $xpath->query("//a");
foreach ($links as $link) {
    $href = $link->getAttribute('href');
    if (substr($href, -1) === '/') {
        $link->setAttribute('href', $href."index.html");
    }
}
$new_file_content = $dom->saveHTML();
# save this wherever you want

参见 ideone.com上的演示


提示:你对$dom->saveHTML()的调用导致无处可去(即没有变量捕获输出)。