0

我有一个脚本,它假设从定义的 url 或页面收集所有 css。我已经尝试了所有方法,但由于某种原因它无法检测到链接的样式表,例如

<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);
}
4

1 回答 1

1

这是一个不错的 DOM/XPath 方式(演示):

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;
}
于 2012-10-14T05:58:46.370 回答