2016-09-20 139 views
0

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

我在做什麼錯?

謝謝。

+0

不知道你在做什麼錯,但'$ html'是從哪裏來的?它不在你的循環或功能中。 – Jan

+0

你說得對,我編輯了代碼,但仍然無法使用。 – Morpheus

回答

0

這是你想要的嗎?

$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 

請參閱a demo on ideone.com


提示:您致電 $dom->saveHTML()導致無處(即沒有變量捕獲輸出)。

+0

我在演示中看到它正在工作,但是當我嘗試此操作時,我得到空文件... index.html或任何其他文件(contact.html,about.html)現在都是空的......某些內容不好。 ..當我做echo $ new_path它顯示只是/索引,/ about /,/ contact /任何其他建議? – Morpheus

+0

@Morpheus:只需使用'file_put_contens(「filename_here」,$ dom-> saveHTML())'而不是搞亂你的東西:) – Jan