parse a HTML string

@param string $html
@return string markdown formatted
979683
function parseString($html) {
    $this->parser->html = $html;
    $this->parse();
    return $this->output;
  }
1065706
public function parseContent( $html ){
		$pattern = '~<p>ADDTEMPLATE\(([\w_:-]*)\):([\w_-]+):ETALPMETDDA<\/p>~m';
		if( preg_match_all($pattern, $html, $matches, PREG_SET_ORDER) ){
			foreach($matches as $match){
				//if a zone is specified, attach the template
				if(!empty($match[1])){
					$this->getLayout()->addTemplateTo($match[1], $match[2]);
					$html = str_replace($match[0], '', $html);
				}else{
				//otherwise inject the template inline into the wikitext
					$html = str_replace($match[0], $this->getLayout()->renderTemplate($match[2]), $html);
				}
			}
		}
		return $html;
	}
1190660
public static function htmlToPlainText($html)
    {
        // Replace &nbsp; with spaces
        $html = str_replace("\xC2\xA0", ' ', html_entity_decode($html));
        // Strip out HTML tags
        $text = strip_tags($html);
        // Replace excessive whitespace (spaces, tabs, and line breaks) with single space
        $text = preg_replace('/\s+/S', ' ', $text);

        return $text;
    }
233870
public function transform($html)
    {
        if (class_exists('HTMLPurifier')) {
            $config = HTMLPurifier_Config::createDefault();
            $purifier = new HTMLPurifier($config);
            $cleanHtml = $purifier->purify($html);
        } else {
            $cleanHtml = strip_tags($html, '<a><b><br><i><p><s><u>');
        }

        return $cleanHtml;
    }
123451
private function prepareHtmlForDomConversion($html)
    {
        $htmlWithSelfClosingSlashes = $this->ensurePhpUnrecognizedSelfClosingTagsAreXml($html);
        $htmlWithDocumentType = $this->ensureDocumentType($htmlWithSelfClosingSlashes);

        return $this->addContentTypeMetaTag($htmlWithDocumentType);
    }
471359
function ReadMetaTags($html)
	{
		// changes anykey=anyvalue to anykey="anyvalue" (only do this when this happens inside tags)
		$regexp = '/ (\\w+?)=([^\\s>"]+)/si';
		$html = preg_replace($regexp, " \$1=\"\$2\"", $html);
		if (preg_match('/<title>(.*?)<\/title>/si', $html, $m)) {
			$this->SetTitle($m[1]);
		}
		preg_match_all('/<meta [^>]*?(name|content)="([^>]*?)" [^>]*?(name|content)="([^>]*?)".*?>/si', $html, $aux);
		$firstattr = $aux[1];
		$secondattr = $aux[3];
		for ($i = 0; $i < count($aux[0]); $i++) {
			$name = ( strtoupper($firstattr[$i]) == "NAME" ) ? strtoupper($aux[2][$i]) : strtoupper($aux[4][$i]);
			$content = ( strtoupper($firstattr[$i]) == "CONTENT" ) ? $aux[2][$i] : $aux[4][$i];
			switch ($name) {
				case "KEYWORDS":
					$this->SetKeywords($content);
					break;
				case "AUTHOR":
					$this->SetAuthor($content);
					break;
				case "DESCRIPTION":
					$this->SetSubject($content);
					break;
			}
		}
	}
8149
public function loadHtml($html)
    {
        if (!is_string($html)) {
            throw new InvalidArgumentException(__METHOD__ . ' expects parameter 1 to be string.');
        }

        libxml_use_internal_errors(true);
        libxml_disable_entity_loader(true);

        $sxe = simplexml_load_string($html);
        if (libxml_get_errors()) {
            $this->document->loadHTML('<?xml encoding="UTF-8">' . $html);
        } else {
            $this->document = dom_import_simplexml($sxe)->ownerDocument;
        }

        libxml_clear_errors();
        libxml_disable_entity_loader(false);
        libxml_use_internal_errors(false);

        return $this;
    }
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;
		}
1341901
public static function Markdown($Mixed) {
      if (!is_string($Mixed)) {
         return self::To($Mixed, 'Markdown');
      } else {         
         $Formatter = Gdn::Factory('HtmlFormatter');
         if (is_null($Formatter)) {
            return Gdn_Format::Display($Mixed);
         } else {
            require_once(PATH_LIBRARY.'/vendors/markdown/markdown.php');
            $Mixed = Markdown($Mixed);
            $Mixed = $Formatter->Format($Mixed);
            $Mixed = Gdn_Format::Links($Mixed);
            $Mixed = Gdn_Format::Mentions($Mixed);
            return $Mixed;
         }
      }
   }
1252196
protected function buildText(string $html): string
    {
        $text = Strings::replace($html, [
            '#<(style|script|head).*</\\1>#Uis' => '',
            '#<t[dh][ >]#i' => ' $0',
            '#<a\s[^>]*href=(?|"([^"]+)"|\'([^\']+)\')[^>]*>(.*?)</a>#is' => '$2 &lt;$1&gt;',
            '#[\r\n]+#' => ' ',
            '#<(/?p|/?h\d|li|br|/tr)[ >/]#i' => "\n$0",
        ]);
        $text = \html_entity_decode(\strip_tags($text), ENT_QUOTES, 'UTF-8');
        $text = Strings::replace($text, '#[ \t]+#', ' ');

        return \trim($text);
    }
1072611
protected function createDomDocumentFromHtml($html)
    {
        $document = new \DOMDocument('1.0', 'UTF-8');
        $internalErrors = libxml_use_internal_errors(true);
        if (!empty($html)) {
            $document->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
        }
        libxml_use_internal_errors($internalErrors);
        $document->formatOutput = true;

        return $document;
    }
1005359
public function convertToString($html)
    {
        $extractedStylesheets = $this->extractExternalStylesheets($html);
        $links = $this->createStylesheetPaths($extractedStylesheets['links']);

        $externalStylesheets =  array(
            'tags' => $extractedStylesheets[0],
            'links' => $links
        );

        $html = $this->replaceExternalCss($html, $externalStylesheets);

        return $html;
    }
469565
def parse_html(html):
    
    paragraphs = re.split("</?p[^>]*>", html)

    # Convert <br>s to line breaks and remove empty paragraphs
    paragraphs = [re.split("<br */?>", p) for p in paragraphs if p]

    # Convert each line in each paragraph to plain text:
    return [[get_text(l) for l in p] for p in paragraphs]
859827
protected function getHtmlFrag($html)
    {
        if (!($html = (string) $html)) {
            return []; // Nothing to do.
        }
        if (preg_match('/(?P<all>(?P<open_tag>\<html(?:\s+[^>]*?)?\>)(?P<contents>.*?)(?P<closing_tag>\<\/html\>))/uis', $html, $html_frag)) {
            return $this->removeNumericKeysDeep($html_frag);
        }
        return [];
    }
1070321
private function parseContents(string $html): string
    {
        if (\trim($html) === '') {
            return '';
        }

        // Determine value.
        $this->value = $html;
        if (\preg_match("/(.*)<\/\s*" . $this->name . "\s*>/iU", $html, $valueMatches) === 1) {
            $this->value = $valueMatches[1];
        }

        // Don't parse contents of "iframe" element.
        if ($this->name === 'iframe') {
            return $this->parseNoContents('iframe', $html);
        }

        // Only TEXT inside a "script" element.
        if ($this->name === 'script') {
            return $this->parseForeignContents('script', $html);
        }

        // Only TEXT inside a "style" element.
        if ($this->name === 'style') {
            return $this->parseForeignContents('style', $html);
        }

        // Parse contents one token at a time.
        $remainingHtml = $html;
        while ($this->isAnotherTokenPresent($remainingHtml)) {
            $token = Tokenizer::buildFromHtml($remainingHtml, $this);

            if (!$token instanceof TokenInterface || $token->isClosingElementImplied($remainingHtml)) {
                return $remainingHtml;
            }

            $remainingHtml = $token->parse($remainingHtml);
            $this->children[] = $token;
        }

        $this->removeLastTokenIfContainsOnlyWhitespace();

        // Remove remaining closing tag.
        $posOfClosingBracket = \mb_strpos($remainingHtml, '>');

        return \mb_substr($remainingHtml, $posOfClosingBracket + 1);
    }
1298470
protected function preventHtmlParserError($html)
    {
        // remove empty tags
        $pattern = "/<[^\/>]*>([\s]?)*<\/[^>]*>/m";
        $html = preg_replace($pattern, '', $html);
        // Run twice just in case we got nested empty tags like figure / figurecaption
        $html = preg_replace($pattern, '', $html);

        return $html;
    }
1049997
public function setHtml($html)
    {
        if (!\is_string($html)) {
            throw new \InvalidArgumentException('The provided HTML must be a string.', 1540403913);
        }
        if ($html === '') {
            throw new \InvalidArgumentException('The provided HTML must not be empty.', 1540403910);
        }

        $this->createUnifiedDomDocument($html);
    }