2012-10-11 46 views
0

我有一個腳本,它假設收集所有的CSS形式的定義的網址或頁面。我曾嘗試一切,由於某種原因,它不會得到它來檢測鏈接的樣式表,如爲CSS引用解析HTML文件

<link rel="stylesheet" href="css/typography.css" /> 

我已經試過所有我能想到的。這是我正在使用的代碼頁CSS和導入收集。任何幫助添加鏈接系統都會很棒。

function scan($page_content){ 
    $i = 0; 
    if(ereg("<style(*[\n]*.*)>\n*(.\n*)*<\/style>", $page_content)){ 
     if(preg_match_all("/(@\s*import\s* (url((\"|')?)?((\"|')?)|(\"|'){1}).+(\"|')?\)?)/", $page_content, $ext_stylesheets)){ 
      foreach($ext_stylesheets[0] as $stylesheet){ 
       $css_content[$i] = preg_replace("/(@\s*import\s*)|(url\(?((\"|')?))|(\"|'){1}|\)?(\"|')?;|(\s)/", "", $stylesheet); 
       $i++; 
      } 
      $array = 1; 
     } 
     $inline_notused = $this->check_file($page_content, $page_content); 
    } 
    else die("No page styles, sorry!".$this->helptext); 
} 
+8

不要使用正則表達式HTML ...使用DOM解析器。 – Brad

+1

我相信你可以使用xPath來解析DOM而不是正則表達式? – Luca

+1

如果你必須使用正則表達式,不要使用ereg。它已被棄用,並將在某些時候從PHP中刪除。 –

回答

1

這裏是一個不錯的DOM/XPath的方式(demo):

function scan($html) { 
    $dom = new DOMDocument; 
    $dom->loadHTML($html); 
    $path = new DOMXPath($dom); 
    $nodes = $path->query('//style|//link'); 
    $style = ''; 
    foreach($nodes as $node) { 
     if($node->tagName === 'style') { 
      $style .= $node->nodeValue; 
     } elseif($node->tagName === 'link') { 
      $style .= "@import url('{$node->getAttribute('href')}')"; 
     } else { 
      // Invalid 
     } 
     $style .= PHP_EOL; 
    } 
    return $style; 
} 
+0

有點看起來像你需要解析用於導入的'