Extract the css files from a html code

@access public
@param  string   &$html
967426
public function readStyle(&$html)
    {
        // the CSS content
        $style = ' ';

        // extract the link tags, and remove them in the html code
        preg_match_all('/<link([^>]*)>/isU', $html, $match);
        $html = preg_replace('/<link[^>]*>/isU', '', $html);
        $html = preg_replace('/<\/link[^>]*>/isU', '', $html);

        // analyse each link tag
        foreach ($match[1] as $code) {
            $tmp = array();

            // read the attributes name=value
            $prop = '([a-zA-Z0-9_]+)=([^"\'\s>]+)';
            preg_match_all('/'.$prop.'/is', $code, $match);
            for ($k=0; $k<count($match[0]); $k++) {
                $tmp[trim(strtolower($match[1][$k]))] = trim($match[2][$k]);
            }

            // read the attributes name="value"
            $prop = '([a-zA-Z0-9_]+)=["]([^"]*)["]';
            preg_match_all('/'.$prop.'/is', $code, $match);
            for ($k=0; $k<count($match[0]); $k++) {
                $tmp[trim(strtolower($match[1][$k]))] = trim($match[2][$k]);
            }

            // read the attributes name='value'
            $prop = "([a-zA-Z0-9_]+)=[']([^']*)[']";
            preg_match_all('/'.$prop.'/is', $code, $match);
            for ($k=0; $k<count($match[0]); $k++) {
                $tmp[trim(strtolower($match[1][$k]))] = trim($match[2][$k]);
            }

            // if type text/css => we keep it
            if (isset($tmp['type']) && strtolower($tmp['type'])=='text/css' && isset($tmp['href'])) {

                // get the href
                $url = $tmp['href'];

                // get the content of the css file
                $content = @file_get_contents($url);

                // if "http://" in the url
                if (strpos($url, 'http://')!==false) {

                    // get the domain "http://xxx/"
                    $url = str_replace('http://', '', $url);
                    $url = explode('/', $url);
                    $urlMain = 'http://'.$url[0].'/';

                    // get the absolute url of the path
                    $urlSelf = $url; unset($urlSelf[count($urlSelf)-1]); $urlSelf = 'http://'.implode('/', $urlSelf).'/';

                    // adapt the url in the css content
                    $content = preg_replace('/url\(([^\\\\][^)]*)\)/isU', 'url('.$urlSelf.'$1)', $content);
                    $content = preg_replace('/url\((\\\\[^)]*)\)/isU', 'url('.$urlMain.'$1)', $content);
                } else {
// @TODO correction on url in absolute on a local css content
                    // $content = preg_replace('/url\(([^)]*)\)/isU', 'url('.dirname($url).'/$1)', $content);
                }

                // add to the CSS content
                $style.= $content."\n";
            }
        }

        // extract the style tags des tags style, and remove them in the html code
        preg_match_all('/<style[^>]*>(.*)<\/style[^>]*>/isU', $html, $match);
        $html = preg_replace('/<style[^>]*>(.*)<\/style[^>]*>/isU', '', $html);

        // analyse each style tags
        foreach ($match[1] as $code) {
            // add to the CSS content
            $code = str_replace('<!--', '', $code);
            $code = str_replace('-->', '', $code);
            $style.= $code."\n";
        }

        //analyse the css content
        $this->_analyseStyle($style);
    }
786940
protected static function processSetLayout($html){
    $pattern = '~<p>LAYOUT:([\w_-]+):TUOYAL<\/p>~m';
    if( preg_match_all($pattern, $html, $matches, PREG_SET_ORDER) ){
      $layout = array_pop($matches);

      self::setLayout($layout[1]);

      $html = preg_replace($pattern, '', $html);
    }
    return $html;
  }
1340746
function parse($html)
		{
			$dom = new \DOMDocument();
			libxml_use_internal_errors(true);
			$dom->loadHTML($html);
			$xpath = new \DOMXPath($dom);
			
			// Load resources for tag actions
			$this->ignoreElements = new ResourceProvider("html_tag_actions/ignore.lst");
			$this->linkElements = new ResourceProvider("html_tag_actions/link.lst");
			$this->bodyElements = new ResourceProvider("html_tag_actions/body.lst");
			$this->inlineElements = new ResourceProvider("html_tag_actions/inline.lst");
			
			/*	
			 *  1st retrieve page title
			 *  With this technique: only process the entire document here 
			 *  as meta is excluded as 'content' and only required for initial title.
			 */

			// Extract title from DOM
			$body = $xpath->query('/')->item(0);
			$titleItem = $xpath->query('//title')->item(0);
			
			if(isset($titleItem))
			{
				$title = $titleItem->textContent;
			}
			$body = $xpath->query('//body')->item(0);
			
			// Try to extract title from OG meta
			foreach ($xpath->query("//meta[@property='og:title']") as $el) 
			{
				$title = $el->getAttribute("content");
			}
			
			$this->recurse($body);
			$Article = new Article();
			if(isset($title))
			{
				$Article->title = $title;
			}
			$Article->textBlocks = $this->textBlocks;
			return $Article;
		}
565285
public static function compress($html)
    {
        $filters = array(
            // remove javascript comments
            '/(?:<script[^>]*>|\G(?!\A))(?:[^\'"\/<]+|"(?:[^\\"]+|\\.)*"|\'(?:[^\\\']+|\\.)*\'|\/(?!\/)|<(?!\/script))*+\K\/\/[^\n|<]*/xsu' => '',
            // remove html comments except IE conditions
            '/<!--(?!\s*(?:\[if [^\]]+]|<!|>))(?:(?!-->).)*-->/su' => '',
            // remove comments in the form /* */
            '/\/+?\s*\*[\s\S]*?\*\s*\/+/u' => '',
            // shorten multiple white spaces
            '/>\s{2,}</u' => '><',
            // shorten multiple white spaces
            '/\s{2,}/u' => ' ',
            // collapse new lines
            '/(\r?\n)/u' => '',
        );

        $output = preg_replace(array_keys($filters), array_values($filters), $html);

        return $output;
    }
291314
public function clean_asset_tags($tag)
    {
        \preg_match_all(
            "!<link rel='stylesheet'\s?(id='[^']+')?\s+href='(.*)' type='text/css' media='(.*)' />!",
            $tag,
            $matches
        );
       
        if (empty($matches[2])) {
            return $tag;
        }

        $media = $matches[3][0] !== '' && $matches[3][0] !== 'all' ? ' media="' . $matches[3][0] . '"' : '';

        return "\t".'<link rel="stylesheet" href="' . $matches[2][0] . '"' . $media . '>' . "\n";
    }
107596
protected function removeEmptyTags($html)
    {
        if (!\is_string($html)) {
            return $html;
        }
        /*
            Toss empty tags such as label or legend
            keep empty textarea
        */
        $html = \preg_replace('#^\s*<(div|label|legend|span)\b[^>]*>\s*</\1>\n#m', '', $html);
        $html = \preg_replace('#^\s*\n#m', '', $html);  // toss empty lines
        $html = \preg_replace('#<(\w+) >#', '<$1>', $html);   // <tab > ->  <tab>
        return $html;
    }
1222630
final public function importHTML($html)
	{
		$tmp_doc = new \DOMDocument('1.0', 'UTF-8');
		$tmp_doc->loadHTML($html);
		$nodes = array();
		foreach ($tmp_doc->documentElement->childNodes as $node) {
			array_push($nodes, $node);
			$this->appendChild($this->ownerDocument->importNode($node, true));
		}
		return $nodes;
	}
866838
public function convert($html)
    {
        preg_match_all('|<img ([^>]+)>|', $html, $matches);

        foreach($matches[0] as $img)
        {
            $crawler = new Crawler();
            $crawler->addContent($img);
            $imgTag = $crawler->filter("img");

            $src = $imgTag->attr('src');
            $width = $imgTag->attr('width');
            $height = $imgTag->attr('height');

            if (!empty($width) || !empty($height)) {
                $format = $width . "x" . $height;
                $updatedTagString = preg_replace("| src=[\"']" . $src . "[\"']|", " src=\"" . $this->imResize($src, $format) . "\"", $img);
                $html = str_replace($img, $updatedTagString, $html);
            }
        }

        return $html;
    }
304513
protected function maybeCompressHtmlCode($html)
    {
        if (($benchmark = !empty($this->options['benchmark']) && $this->options['benchmark'] === 'details')) {
            $time = microtime(true);
        }
        $html = (string) $html; // Force string value.

        if (isset($this->options['compress_html_code'])) {
            if (!$this->options['compress_html_code']) {
                $disabled = true; // Disabled flag.
            }
        }
        if (!$html || !empty($disabled)) {
            goto finale; // Nothing to do.
        }
        if (($compressed_html = $this->compressHtml($html))) {
            $html = $compressed_html; // Use it :-)
        }
        finale: // Target point; finale/return value.

        if ($html) {
            $html = trim($html);
        } // Trim it up now!

        if ($benchmark && !empty($time) && $html && empty($disabled)) {
            $this->benchmark->addTime(
                __FUNCTION__,
                $time, // Caller, start time, task performed.
                sprintf('compressing HTML w/ checksum: `%1$s`', md5($html))
            );
        }
        return $html; // With possible compression having been applied here.
    }
538135
public function convert($html)
    {
        $html = parent::convert((string) $html);

        $html = $this->encode('--', '-', $html, false);
        $html = $this->encode('\#', '#', $html);
        $html = $this->encode('\*', '*', $html);
        $html = $this->encode('\_', '_', $html);
        $html = $this->encode('•', '*', $html);
        $html = $this->encode('…', '...', $html);

        $html = $this->encode('\[', '[', (string) $html);
        $html = $this->encode('\]', ']', (string) $html);
        $html = str_replace(array('—', '–', '\-'), '-', $html);
        $html = str_replace(array('“', '”'), '"', $html);
        $html = str_replace(array('’', '‘'), "'", $html);
        $html = str_replace("\n\n\n", "\n\n", $html);
        $html = str_replace("\n ", "\n", (string) $html);

        return str_replace('\.', '.', (string) $html);
    }
1353265
public function get($html = null)
    {
        if (null === $html) {
            if (file_exists($this->_path)) {
                $html = file_get_contents($this->_path);
            }
        }

        $this->_path = null;

        return $this->parse($html);
    }
651861
private function extractMetas(DOMDocument $html)
    {
        foreach ($html->getElementsByTagName('meta') as $meta) {
            $value = $meta->getAttribute('content');

            if (empty($value)) {
                continue;
            }

            if ($meta->hasAttribute('name')) {
                $name = trim(strtolower($meta->getAttribute('name')));

                switch ($name) {
                    case 'msapplication-tileimage':
                        $this->bag->add('icons', $value);
                        continue 2;

                    default:
                        $this->bag->set($name, $value);
                        continue 2;
                }
            }

            if ($meta->hasAttribute('itemprop')) {
                $this->bag->set($meta->getAttribute('itemprop'), $value);
            }

            if ($meta->hasAttribute('http-equiv')) {
                $this->bag->set($meta->getAttribute('http-equiv'), $value);
            }

            if ($meta->hasAttribute('property')) {
                $this->bag->set($meta->getAttribute('property'), $value);
            }
        }
    }
533288
public function wash($html)
    {
        // Charset seems to be ignored (probably if defined in the HTML document)
        $node = new DOMDocument('1.0', $this->config['charset']);
        $this->extlinks = false;

        $html = $this->cleanup($html);

        // Find base URL for images
        if (preg_match('/<base\s+href=[\'"]*([^\'"]+)/is', $html, $matches)) {
            $this->config['base_url'] = $matches[1];
        }
        else {
            $this->config['base_url'] = '';
        }

        // Detect max nesting level (for dumpHTML) (#1489110)
        $this->max_nesting_level = (int) @ini_get('xdebug.max_nesting_level');

        // SVG need to be parsed as XML
        $this->is_xml = stripos($html, '<html') === false && stripos($html, '<svg') !== false;
        $method       = $this->is_xml ? 'loadXML' : 'loadHTML';
        $options      = 0;

        // Use optimizations if supported
        if (PHP_VERSION_ID >= 50400) {
            $options = LIBXML_PARSEHUGE | LIBXML_COMPACT | LIBXML_NONET;
            @$node->{$method}($html, $options);
        }
        else {
            @$node->{$method}($html);
        }

        return $this->dumpHtml($node);
    }
502629
public function parse($html)
    {
        if (!is_array($html)) {
            if (file_exists($html)) {
                $html = file($html);
            } else {
                return "Error opening template file $html";
            }
        }
        $return = '';
        foreach ($html as $line) {
            $return .= preg_replace_callback('/\<dynamic\s+name\s*=\s*[\'"](\S+?)[\'"]\>/i', [&$this, 'replace'], $line);
        }

        return $return;
    }
730593
protected function restore($html)
    {
        foreach ($this->data as $index => $item)
        {
            $key = (string) '$' . $index . '$';

            $html = str_replace($key, $item, $html);
        }

        return (string) $html;
    }
765374
private function extractStyleSheet(Element $element){
        if($element instanceof StyleSheet){
            $href = $element->attr('href');
            $this->addAsset('css', $href);

            $parsedUrl = parse_url($href);
            if ($this->isDeepParsing() && array_key_exists('path', $parsedUrl) && !array_key_exists('host',
                    $parsedUrl)
            ) {
                $file = $this->directory->getFile($parsedUrl['path']);
                if ($file->exists()) {
                    $this->loadStyleSheetAsset($file->read());
                }
            }
        }
    }
8896
protected function stripHtml($html)
    {
        $str = html_entity_decode($html);

        // Strip HTML (Replace br with newline, remove "invisible" tags and strip other tags)
        $str = preg_replace('#<br[^>]*?>#siu', "\n", $str);
        $str = preg_replace(
            [
                '#<applet[^>]*?.*?</applet>#siu',
                '#<embed[^>]*?.*?</embed>#siu',
                '#<head[^>]*?>.*?</head>#siu',
                '#<noframes[^>]*?.*?</noframes>#siu',
                '#<noscript[^>]*?.*?</noscript>#siu',
                '#<noembed[^>]*?.*?</noembed>#siu',
                '#<object[^>]*?.*?</object>#siu',
                '#<script[^>]*?.*?</script>#siu',
                '#<style[^>]*?>.*?</style>#siu'
            ],
            '',
            $str
        );
        $str = strip_tags($str);

        // Trim whitespace
        $str = str_replace("\t", '', $str);
        $str = preg_replace('#\n\r|\r\n#', "\n", $str);
        $str = preg_replace('#\n{3,}#', "\n\n", $str);
        $str = preg_replace('/ {2,}/', ' ', $str);
        $str = implode("\n", array_map('trim', explode("\n", $str)));
        $str = trim($str)."\n";
        return $str;
    }