Parse the text.

The actual logic of this function is to setup the XML parsing extension.

@param string $html

@return string
355037
public function toText($html)
    {
        $parser = new Parser();

        $xmlParser = xml_parser_create();
        xml_set_element_handler($xmlParser, [$parser, 'startElement'], [$parser, 'endElement']);
        xml_set_character_data_handler($xmlParser, [$parser, 'characterData']);

        $wrappedHtml = "<root>$html</root>";
        $returnStatus = xml_parse($xmlParser, $wrappedHtml, true);

        if (!$returnStatus) {
            return $html;
        }

        return $parser->getText();
    }
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);
    }
324149
public final Element parse(final String html) {
        checkNotNull(html, "Received a null pointer as body");

        return Jsoup.parse(html).body();
    }
342133
private function parseElementName(string $html): string
    {
        $html = \trim($html);
        $elementMatchSuccessful = \preg_match(
            "/^(<(([a-z0-9\-]+:)?[a-z0-9\-]+))/i",
            $html,
            $elementMatches
        );
        if ($elementMatchSuccessful !== 1) {
            if ($this->getThrowOnError()) {
                throw new ParseException('Invalid element name. Truncated html = ' . \mb_substr($html, 0, 20));
            }

            return '';
        }

        return \mb_strtolower($elementMatches[2]);
    }
812897
public function loadHTML($html)
    {
        $dom = new \DOMDocument();

        libxml_use_internal_errors(true);
        $dom->loadHTML($html, LIBXML_NOWARNING);
        $errors = libxml_get_errors();
        libxml_use_internal_errors(false);

        // Run through all errors
        /** @var \LibXMLError $error */
        foreach ($errors as $error) {
            throw new InvalidArgumentException(
                sprintf(InvalidArgumentException::INVALID_HTML_STR, trim($error->message)),
                InvalidArgumentException::INVALID_HTML
            );
        }

        return $dom;
    }
601336
public function parse($text) {
        $this->text = $text;

        $data = array();
        $indcheck = array();

        $c = strlen($this->text);
        for ($i = 0; $i < $c; $i++) {
            $pos = array_search($this->text[$i], $this->keys);
            if ($pos === false) {
                // Search in extended?
                $extended = self::getExtendedVersion($this->text[$i]);
                if ($extended === false) {
                    throw new CINParseException('code93', 'The character \'' . $this->text[$i] . '\' is not allowed.');
                } else {
                    $extc = strlen($extended);
                    for ($j = 0; $j < $extc; $j++) {
                        $v = $extended[$j];
                        if ($v === '$') {
                            $indcheck[] = self::EXTENDED_1;
                            $data[] = $this->code[self::EXTENDED_1];
                        } elseif ($v === '%') {
                            $indcheck[] = self::EXTENDED_2;
                            $data[] = $this->code[self::EXTENDED_2];
                        } elseif ($v === '/') {
                            $indcheck[] = self::EXTENDED_3;
                            $data[] = $this->code[self::EXTENDED_3];
                        } elseif ($v === '+') {
                            $indcheck[] = self::EXTENDED_4;
                            $data[] = $this->code[self::EXTENDED_4];
                        } else {
                            $pos2 = array_search($v, $this->keys);
                            $indcheck[] = $pos2;
                            $data[] = $this->code[$pos2];
                        }
                    }
                }
            } else {
                $indcheck[] = $pos;
                $data[] = $this->code[$pos];
            }
        }

        $this->setData(array($indcheck, $data));
        $this->addDefaultLabel();
    }
116761
public function parseString($html)
    {
        /** TODO: custom markdown-extra options, e.g. titles & classes **/
        // <sup id="fnref:..."><a href"#fn..." rel="footnote">...</a></sup>
        // => <fnref target="..." />
        $html = preg_replace('@<sup id="fnref:([^"]+)">\s*<a href="#fn:\1" rel="footnote">\s*\d+\s*</a>\s*</sup>@Us', '<fnref target="$1" />', $html);
        // <div class="footnotes">
        // <hr />
        // <ol>
        //
        // <li id="fn:...">...</li>
        // ...
        //
        // </ol>
        // </div>
        // =>
        // <footnotes>
        //   <fn name="...">...</fn>
        //   ...
        // </footnotes>
        $html = preg_replace_callback('#<div class="footnotes">\s*<hr />\s*<ol>\s*(.+)\s*</ol>\s*</div>#Us', [&$this, '_makeFootnotes'], $html);

        return parent::parseString($html);
    }
521830
protected static function parseReleases($html)
    {
        $releases         = array();
        $xmlErrorHandling = libxml_use_internal_errors(true);

        $dom = new DOMDocument();
        $dom->loadHTML($html);
        $xpath = new DOMXPath($dom);

        $nodes = self::getByClass('version', $xpath);
        foreach ($nodes as $node) {
            $version = $node->getAttribute('id');
            if (1 !== preg_match(self::SKIP_PATTERN, $version)) {
                $date      = '';
                $dateNodes = self::getByClass('releasedate', $xpath, $node);
                foreach ($dateNodes as $dateNode) {
                    $date = $dateNode->getAttribute('datetime');
                }
                $releases[$version] = empty($date) ? '' : $date;
            }
        }

        libxml_clear_errors();
        libxml_use_internal_errors($xmlErrorHandling);

        return (array)$releases;
    }
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);
    }
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;
    }
1334076
public function html2text($html, $advanced = false)
    {
        if ($advanced) {
            require_once 'extras/class.html2text.php';
            $htmlconverter = new html2text($html);
            return $htmlconverter->get_text();
        }
        return html_entity_decode(
            trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
            ENT_QUOTES,
            $this->CharSet
        );
    }
156483
public function convert($html)
    {
        // Remove \r
        $html = str_replace("\r", "", $html);

        $doc = new DOMDocument();
        if (!$doc->loadHTML($html)) {
            throw new Exception("Failed to load html string");
        }

        // Walk the DOM document to convert to plain text
        $output = $this->processNode($doc);

        // Remove leading and trailing spaces on each line
        $output = preg_replace("/[ \t]*\n[ \t]*/im", "\n", $output);

        // Word wrap if required
        if ($this->wrapColumn) {
            $output = wordwrap($output, $this->wrapColumn);
        }

        // Remove leading and trailing whitespace
        $output = trim($output);

        // Add a final new line
        $output .= "\n";

        return $output;
    }
173757
public function parse() {
		if($this->bParsed) {
			return;
		}

		if ($this->replacements) {
            // We cannot rely of html_entity_decode,
            // because it would replace &amp; and &lt; as well,
            // whereas we need to keep them unmodified.
            // We must do it manually, with a modified hardcopy
            // of PHP 5.4+ 's get_html_translation_table(ENT_XHTML)
            $this->source = XMLEntityTransformer::replace($this->source);
		}
		
		$this->xmlParser = xml_parser_create('UTF-8');
		xml_parser_set_option($this->xmlParser, XML_OPTION_CASE_FOLDING, false);
		xml_set_object($this->xmlParser, $this);
		xml_set_element_handler($this->xmlParser, 'openTagHandler', 'closeTagHandler');
		xml_set_character_data_handler($this->xmlParser,'cdataHandler');

		//Prepare the detection of the very first tag, in order to compute
		//the offset in XML string as regarded by the parser.
		$this->firstOpening = true;

		try {
            $bSuccess = xml_parse($this->xmlParser, $this->source);
        } catch (RequiredAttributeException $ex) {
		    throw $ex->setFile($this->filename);
        }

        if ($bSuccess) {
            $errMsg = '';
            $lineNumber = 0;
        } else {
			$errMsg = xml_error_string(xml_get_error_code($this->xmlParser));
			$lineNumber = xml_get_current_line_number($this->xmlParser);
			if(count($this->stack)) {
				$lastElement = $this->stack[count($this->stack) - 1];
				if($lastElement instanceof ViewElementTag) {
					$errMsg .= '. Last element: ' . $lastElement->getTagName() . '(' . $lineNumber . ')';
				}
			}
		}

		xml_parser_free($this->xmlParser);
		$this->bParsed = $bSuccess;

		if(! $bSuccess ) {
			throw new XMLParsingException(
					$errMsg,
					$lineNumber);
		}

		// Store a serialized version of the parsed tree, if successfully parsed,
        // and if we've got a cache path.
        if ( ($this->cachePath) && ($this->filename !== null) && (! $this->unserialized) ) {
            $cacheFile = $this->makeCacheFilename($this->cachePath, $this->templatesRoot, $this->filename, true);
            file_put_contents($cacheFile, serialize($this));
        }


    }
1149578
public function tokenize($html)
    {
        // initialise the array
        $tokens = array();

        // regexp to separate the tags from the texts
        $reg = '/(<\/?\w[^<>]*>)|([^<]+|<)/is';
        $commentRegex = '/(<!--.*-->)/isU';

        // last match found
        $str = '';
        $offset = 0;
        $line = 1;
        $length = strlen($html);

        // As it finds a match
        while ($offset < $length) {
            if (strpos($html, '<!--', $offset) === $offset
                && preg_match($commentRegex, $html, $match, PREG_OFFSET_CAPTURE, $offset)
            ) {
                $line += substr_count($match[1][0], "\n");
                $offset = $match[0][1] + strlen($match[0][0]);
                continue;
            }
            preg_match($reg, $html, $parse, PREG_OFFSET_CAPTURE, $offset);
            // if it is a tag
            if ($parse[1][0]) {
                // save the previous text if it exists
                if ($str !== '') {
                    $tokens[] = new Token('txt', $str);
                }

                // save the tag, with the offset
                $tokens[] = new Token('code', trim($parse[1][0]), $line);
                $line += substr_count($parse[1][0], "\n");

                // init the current text
                $str = '';
            } else { // else (if it is a text)
                // add the new text to the current text
                $str .= $parse[2][0];
                $line += substr_count($parse[2][0], "\n");
            }

            // Update offset to the end of the match
            $offset = $parse[0][1] + strlen($parse[0][0]);
            unset($parse);
        }
        // if a text is present in the end, we save it
        if ($str !== '') {
            $tokens[] = new Token('txt', $str);
        }

        return $tokens;
    }
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;
  }
590952
public function loadHTML($html)
    {
        if ($html instanceof Renderable) {
            $html = $html->render();
        }
        $this->html = $html;
        $this->file = null;
        return $this;
    }
728423
public function setHTML($html)
    {
        $node = $this->createDocumentFragment();
        $node->appendXML('<html xmlns="http://www.w3.org/1999/xhtml">'.$html.'</html>');
        $this->doc->appendChild($node);
    }