我正在使用一个小脚本将绝对链接转换为相对的链接。它正在工作,但需要改进。不知道如何继续。请看看这个脚本的一部分。使用正则表达式或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
,但它不工作。我想在这里实现的是,如果链接中的最后一个字符是/
我在做什么错?
谢谢。
不知道你在做什么错,但'$ html'是从哪里来的?它不在你的循环或功能中。 – Jan
你说得对,我编辑了代码,但仍然无法使用。 – Morpheus