我正在使用一個小腳本將絕對鏈接轉換爲相對的鏈接。它正在工作,但需要改進。不知道如何繼續。請看看這個腳本的一部分。使用正則表達式或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