2016-09-20 122 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