繁体   English   中英

使用正则表达式或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);

            }
        }
    }

}

如您所见,我在DOMDocument while loop中添加了它,但是它不起作用。 我要在此处实现的目标是,如果该链接中的最后一个字符为/,则在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()调用无处可寻(即,没有变量捕获输出)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM