Parse the text for script tags

@param string Block of text to parse
@return string
329175
protected function _parseScripts(&$text)
    {
        $scripts = '';

        $matches = array();
        // <script src="" />
        if (preg_match_all('#<script(?!\s+data\-inline\s*)\s+src="([^"]+)"(.*)/>#siU', $text, $matches)) {
            foreach (array_unique($matches[1]) as $key => $match) {
                $attribs = $this->_parseAttributes($matches[2][$key]);
                $scripts .= $this->_renderScript($match, true, $attribs);
            }

            $text = str_replace($matches[0], '', $text);
        }

        $matches = array();
        // <script></script>
        if (preg_match_all('#<script(?!\s+data\-inline\s*)(.*)>(.*)</script>#siU', $text, $matches)) {
            foreach ($matches[2] as $key => $match) {
                $attribs = $this->_parseAttributes($matches[1][$key]);
                $scripts .= $this->_renderScript($match, false, $attribs);
            }

            $text = str_replace($matches[0], '', $text);
        }

        return $scripts;
    }
1197543
public function parse($str)
	{
		$str      = str_replace("\r", "", $str);
		$len      = strlen($str);
		$tag_open = false;
		$tag_text = '';
		$tag      = '';

		// set the document as the current tag.
		$this->current_tag = $this;

		for($i=0; $i<$len; ++$i)
		{
			if($str[$i] === '[')
			{
				if($tag_open)
					$tag_text .= '[' . $tag;

				$tag_open = true;
				$tag      = '';
			}
			else if($str[$i] === ']' && $tag_open)
			{
				if($tag !== '')
				{
					$bits        = preg_split('/([ =])/', trim($tag), 2, PREG_SPLIT_DELIM_CAPTURE);
					$tag_attrs   = (isset($bits[2]) ? $bits[1] . $bits[2] : '');
					$tag_closing = ($bits[0][0] === '/');
					$tag_name    = ($bits[0][0] === '/' ? substr($bits[0], 1) : $bits[0]);

					if(isset($this->bbcodes[$tag_name]))
					{
						$this->tag_text($tag_text);
						$tag_text = '';

						if($tag_closing)
						{
							if(!$this->tag_close($tag_name))
								$tag_text = "[{$tag}]";
						}
						else
						{
							if(!$this->tag_open($tag_name, $this->parse_attribs($tag_attrs)))
								$tag_text = "[{$tag}]";
						}
					}
					else
						$tag_text .= "[{$tag}]";
				}
				else
					$tag_text .= '[]';

				$tag_open = false;
				$tag      = '';
			}
			else if($tag_open)
				$tag .= $str[$i];
			else
				$tag_text .= $str[$i];
		}

		$this->tag_text($tag_text);

		if($this->throw_errors && !$this->current_tag instanceof Node_Container_Document)
			throw new Exception_MissingEndTag("Missing closing tag for tag [{$this->current_tag->tag()}]");

		return $this;
	}
731116
private function parseTagBlock(string $tags, Types\Context $context): array
    {
        $tags = $this->filterTagBlock($tags);
        if (!$tags) {
            return [];
        }

        $result = $this->splitTagBlockIntoTagLines($tags);
        foreach ($result as $key => $tagLine) {
            $result[$key] = $this->tagFactory->create(trim($tagLine), $context);
        }

        return $result;
    }
1136271
function decodeBlocks(script, encoded) {
      while (encoded.test(script)) {
        script = script.replace(global(encoded), function(match, index) {
          return blocks[index];
        });
      }
      return script;
    }
1049475
public function parse($docblock)
    {
        // parse @key value
        preg_match_all('#@([a-zA-Z]+)(.*)(\*/|\n)#', $docblock, $out, PREG_SET_ORDER);

        // compile data
        $annotations = [];
        foreach($out as $row) {
            $key = trim($row[1]);
            $annotations[$key] = $this->resolveValue($row[2]);
        }

        return $annotations;
    }
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);
    }
1333981
private static function parseAnnotations($docblock)
    {
        $annotations = array();

        // Strip away the docblock header and footer to ease parsing of one line annotations
        $docblock = substr($docblock, 3, -2);

        if (preg_match_all('/@(?<name>[A-Za-z_-]+)[\s\t]*\((?<args>(?:(?!\)).)*)\)\r?/s', $docblock, $matches)) {
            $numMatches = count($matches[0]);

            for ($i = 0; $i < $numMatches; ++$i) {
                // annotations has arguments
                if (isset($matches['args'][$i])) {
                    $argsParts = trim($matches['args'][$i]);
                    $name      = $matches['name'][$i];
                    $value     = self::parseArgs($argsParts);
                } else {
                    $value = array();
                }

                $annotations[$name][] = $value;
            }
        }

        return $annotations;
    }
486869
public function parseLines()
    {
        $text = [];

        while (($line = $this->nextLine()) !== false) {
            $line = rtrim($line);

            // Skip empty lines
            if ($line == "") {
                $text[] = null;
                continue;
            }

            // Look at start of line to detect valid blocktypes
            $blockTypes = [];
            $marker = $line[0];
            if (isset($this->blockTypes[$marker])) {
                foreach ($this->blockTypes[$marker] as $blockType) {
                    $blockTypes[] = $blockType;
                }
            }

            // Check if line is matching a detected blocktype
            foreach ($blockTypes as $blockType) {
                if ($this->{"block".$blockType}($line)) {
                    continue;
                }
            }
        }

        $text = implode("\n", $this->lines);

        return [
            "text" => $text,
            "frontmatter" => $this->frontmatter,
        ];
    }
48144
function parse_html() {
      var reading_js = false, reading_css = false;
      var parser = new htmlparser.Parser({
        onopentag: function(name, attribs){
          if (name === "script" && ! attribs.src && (attribs.type === "text/javascript" || ! attribs.type)){
            reading_js = true;
          }
          else if (name === "style") {
            reading_css = true;
          }
        },
        ontext: function(text){
          if (reading_js) {
            scripts.push(text);
          }
          if (reading_css) {
            styles.push(text);
          }
        },
        onclosetag: function(tagname){
          if (tagname === "script"){
            reading_js = false;
          }
          else if (tagname === "style"){
            reading_css = false;
          }
        }
      });
      parser.write(src);
      parser.end();

      return true;
    }
1087605
public function parse($text)
    {
        preg_match_all($this->shortcodeRegex, $text, $matches, PREG_OFFSET_CAPTURE);

        // loop instead of array_map to pass the arguments explicitly
        $shortcodes = array();
        foreach($matches[0] as $match) {
            $offset = mb_strlen(substr($text, 0, $match[1]), 'utf-8');
            $shortcodes[] = $this->parseSingle($match[0], $offset);
        }

        return array_filter($shortcodes);
    }
917389
public static function parseDocCommentDetail($block)
    {
        $comment = strtr(trim(preg_replace('/^\s*\**( |\t)?/m', '', trim($block, '/'))), "\r", '');
        if (preg_match('/^\s*@\w+/m', $comment, $matches, PREG_OFFSET_CAPTURE)) {
            $comment = trim(substr($comment, 0, $matches[0][1]));
        }

        if (empty($comment)) {
            return '';
        }

        $summary = self::parseDocCommentSummary($block);
        $pos = strpos($comment, $summary);
        if ($pos !== false) {
            $comment = trim(substr_replace($comment, '', $pos, strlen($summary)));
        }

        return $comment;
    }
729473
function parseBlock(tokens) {
  if (tokens.type === 'blockquote') {
    return [getBlockquoteToken(tokens)];
  } else if (tokens.type === 'bullet_list' && tokens.content.type === 'list_item' ||
    tokens.type === 'ordered-list' && tokens.content.type === 'list_item') {
    return [getListToken(tokens)];
  }
  return tokens;
}
1049021
protected function _parseTags(&$text)
    {
        $tags = '';

        $matches = array();
        if(preg_match_all('#<ktml:style\s+src="([^"]+)"(.*)\/>#siU', $text, $matches))
        {
            foreach(array_unique($matches[1]) as $key => $match)
            {
                //Set required attributes
                $attribs = array(
                    'src' => $match
                );

                $attribs = array_merge($this->parseAttributes( $matches[2][$key]), $attribs);
                $tags .= $this->_renderTag($attribs);
            }

            $text = str_replace($matches[0], '', $text);
        }

        $matches = array();
        if(preg_match_all('#<style(.*)>(.*)<\/style>#siU', $text, $matches))
        {
            foreach($matches[2] as $key => $match)
            {
                $attribs = $this->parseAttributes( $matches[1][$key]);
                $tags .= $this->_renderTag($attribs, $match);
            }

            $text = str_replace($matches[0], '', $text);
        }

        return $tags;
    }
1271629
public static function parseBlock($block)
    {
        $data = array();
        $lines = preg_split("/(\r\n|\n|\r)/", trim($block));
        $continueKey = null;
        foreach($lines as $n => $line) {
            if ($continueKey !== null) {
                $data[$continueKey] .= "\n" . $line;
                if (!self::lineContinues($lines, $n, $continueKey)) {
                    $continueKey = null;
                }
            } elseif (preg_match('/([^:]*): ?(.*)/', $line, $match)) {
                $key = $match[1];
                $value = $match[2];
                // Convert multiple keys like 'FieldStateOption' or 'FieldValue'
                // from Choice fields to array
                if (isset($data[$key])) {
                    $data[$key]   = (array) $data[$key];
                    $data[$key][] = $value;
                } else {
                    $data[$key] = $value;
                }
                if (self::lineContinues($lines, $n, $key)) {
                    $continueKey = $key;
                }
            }
        }
        return $data;
    }
1355376
function(block) {
  if (block.hasOwnProperty('htmlslabs')) {
    return outputSlabsAsText(block.htmlslabs);
  } else {
    if (block.format === 'section') {
      return block.blocks.reduce(function(previousValue, currentValue, currentIndex, array) {
        return previousValue + extractTextBlockText(currentValue);
      }, '');
    } else {
      return '';
    }
  }
}
1223015
private function parseInlineHtml($text)
	{
		if (strpos($text, '>') !== false) {
			// convert a name markers to \labels
			if (preg_match('~^<((a|span)) (name|id)="(.*?)">.*?</\1>~i', $text, $matches)) {
				return [
					['label', 'name' => str_replace('#', '::', $this->labelPrefix . $matches[4])],
					strlen($matches[0])
				];
			}
		}
		return [['text', '<'], 1];
	}
889502
public static function parseSelector($text){
		$text = preg_replace('/(\>|\+|~)\s+/is', '$1', $text);
		
		$selector	= null;
		
		foreach(preg_split('/\s+/', $text, -1, PREG_SPLIT_NO_EMPTY) as $part){
			if(!preg_match('/^([\>\+~]?)([^ >\+~]+)$/is', $part, $matches)) throw new \Exception("Invalid selector part '$part'");
			
			$selector = $selector ? $selector->add($matches[1] ? $matches[1] : false) : Selector::create();
			
			$offset = 0;
			
			$subtext = $matches[2];
			while($offset < strlen($subtext)){
				if(!preg_match('/^([\.:#]?)((:?[a-z0-9\-]|\*)+)/is', substr($subtext, $offset), $matches)) throw new \Exception("Invalid property at '".substr($text, $offset, 20)."'");
				
				switch($matches[1]){
					case '': $selector->setTagName($matches[2]); break;
					case '#': $selector->setIdentification($matches[2]); break;
					case '.': $selector->addClass($matches[2]); break;
					case ':': $selector->addPseudo($matches[2]); break;
					default: throw new \Exception("Knonwn type '".$matches[1]."'");
				}

				$offset+= strlen($matches[0]);
			}
		}

		return $selector->get();
	}