Detect and extract inline variables.

@param string $text to parse.

@return boolean|void true when block is found and parsed, else void.

@SuppressWarnings(PHPMD.CyclomaticComplexity)
967006
protected function getVariableValue(array $matches)
    {
        $res = $matches[0];
        $variable = substr($matches[0], 1, -1);

        if (isset($this->frontmatter[$variable])) {
            $res = $this->frontmatter[$variable];
        }

        return $res;
    }
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);
    }
994358
private function parseContent($text) {
        /* $yAlreadySet has 3 states: */
        /* null: There is no variable in the ID; true: the variable is already set; false: the variable is not set yet; */
        $content = null;
        $yAlreadySet = null;
        $realNameId = null;
        $separatorsFound = 0;
        $checksumAdded = 0;
        $decimalPointRemoved = 0;
        $toParse = str_replace('~F1', chr(29), $text);
        $nbCharToParse = strlen($toParse);
        $nbCharId = 0;
        $isFormated = $toParse[0] === '(' ? true : false;
        $maxCharId = $isFormated ? self::MAX_ID_FORMATED : self::MAX_ID_NOT_FORMATED;
        $id = strtolower(substr($toParse, 0, min($maxCharId, $nbCharToParse)));
        $id = $isFormated ? $this->findIdFormated($id, $yAlreadySet, $realNameId) : $this->findIdNotFormated($id, $yAlreadySet, $realNameId);

        if ($id === false) {
            if ($this->allowsUnknownIdentifier === false) {
                return false;
            }

            $id = null;
            $nbCharId = 0;
            $content = $toParse;
        } else {
            $nbCharId = strlen($id) + ($isFormated ? 2 : 0);
            $n = min($this->identifiersAi[$realNameId][self::MAXLENGTH], $nbCharToParse);
            $content = substr($toParse, $nbCharId, $n);
        }

        if ($id !== null) {
            /* If we have an AI with an "y" var, we check if there is a decimal point in the next *MAXLENGTH* characters */
            /* if there is one, we take an extra character */
            if ($yAlreadySet !== null) {
                if (strpos($content, '.') !== false || strpos($content, ',') !== false) {
                    $n++;
                    if ($n <= $nbCharToParse) {
                        /* We take an extra char */
                        $content = substr($toParse, $nbCharId, $n);
                    }
                }
            }
        }

        /* We check for separator */
        $separator = strpos($content, chr(29));
        if ($separator !== false) {
            $content = substr($content, 0, $separator);
            $separatorsFound++;
        }

        if ($id !== null) {
            /* We check the conformity */
            if (!$this->checkConformity($content, $id, $realNameId)) {
                return false;
            }

            /* We check the checksum */
            if (!$this->checkChecksum($content, $id, $realNameId, $checksumAdded)) {
                return false;
            }

            /* We check the vars */
            if (!$this->checkVars($content, $id, $yAlreadySet, $decimalPointRemoved)) {
                return false;
            }
        }

        $this->identifiersId[] = $id;
        $this->identifiersContent[] = $content;

        $nbCharLastContent = (((strlen($content) + $nbCharId) - $checksumAdded) + $decimalPointRemoved) + $separatorsFound;
        if ($nbCharToParse - $nbCharLastContent > 0) {
            /* If there is more than one content in this array, we parse again */
            $otherContent = substr($toParse, $nbCharLastContent, $nbCharToParse);
            $nbCharOtherContent = strlen($otherContent);

            if ($otherContent[0] === chr(29)) {
                $otherContent = substr($otherContent, 1);
                $nbCharOtherContent--;
            }

            if ($nbCharOtherContent > 0) {
                $text = $otherContent;
                return $this->parseContent($text);
            }
        }

        return true;
    }
407268
private function tag_get_type(string $text){
    if (
      ($this->mode === 'js') ||
      ($this->mode === 'vue')
    ){
      preg_match('/(?:\{)(.+)(?:\})/', $text, $type, PREG_OFFSET_CAPTURE);
    }
    else if ( $this->mode === 'php' ){
      preg_match('/(?:\@[a-z]+\s{1})(.+)(?:\s{1}\$)/', $text, $type, PREG_OFFSET_CAPTURE);
      $type[0] = $type[1];
    }
    return $type;
  }
677497
public function parse(string $text)
    {
        try {
            $result = $this->syntax->parse($text);
            $this->success = true;
        } catch (ParseException $e) {
            $result = $this->default;
            $this->success = false;
        }

        return $result;
    }
1238749
private function _checkConstantNaming($text) {
		if ($this->_isActive('constantNaming')) {
			$text = ltrim($text, "\"'"); // just in case, remove the quotes
			$text = rtrim($text, "\"'");
			$ret = preg_match($this->_config->getTestRegExp('constantNaming'), $text);
			if (!$ret) {
				$msg = $this->_getMessage('CONSTANT_NAMING', $text, $this->_config->getTestRegExp('constantNaming'));
				$this->_writeError('constantNaming', $msg);
			}
		}
		$this->_constantDef = false;
	}
443081
protected function processBlock($text)
    {
        // Process heading
        if (preg_match(self::MATCH_HEADING, $text, $matches)) {
            return $this->addHeading(strlen($matches[1]), $matches[2]);
        }

        if (preg_match(self::MATCH_HR, $text)) {
            return $this->addHorizontalRule($text);
        }

        if (mb_substr($text, 0, 2) === self::BLOCKQUOTE_START) {
            return $this->processBlockquote($text);
        }

        // nothing found wrap in paragraph
        return $this->processParagraph($text);
   }
755989
public function parse($text) {
        parent::parse($text);

        $number = self::executeStep1($this->text, $this->barcodeIdentifier, $this->serviceTypeIdentifier, $this->mailerIdentifier, $this->serialNumber);
        $crc = self::executeStep2($number);
        $codewords = self::executeStep3($number);
        $codewords = self::executeStep4($codewords, $crc);
        $characters = self::executeStep5($codewords, $crc);
        $this->data = self::executeStep6($characters);
    }
1357410
protected function parseStrong($text)
	{
		$pattern =<<< REGEXP
/^\*\*(
  (.*?{{{.*?}}}.*?)+?|  # including inline code span
  (?!.*{{{.*?}}}).*?    # without inline code span
)\*\*/sx
REGEXP;
		if (preg_match($pattern, $text, $matches)) {
			return [
				[
					'strong',
					$this->parseInline($matches[1])
				],
				strlen($matches[0])
			];
		} else {
			// no ending ** ... should be treated as strong
			return [
				[
					'strong',
					$this->parseInline(substr($text,2))
				],
				strlen($text)
			];
		}
	}
155412
public function parse($text)
    {
        $nestingLevel = ini_set('xdebug.max_nesting_level', -1);
        $this->tokens = $this->tokenize($text);
        $this->backtracks = array();
        $this->lastBacktrack = 0;
        $this->position = 0;
        $this->tokensCount = \count($this->tokens);

        $shortcodes = array();
        while($this->position < $this->tokensCount) {
            while($this->position < $this->tokensCount && false === $this->lookahead(self::TOKEN_OPEN)) {
                $this->position++;
            }
            $names = array();
            $this->beginBacktrack();
            $matches = $this->shortcode($names);
            if(false === $matches) {
                $this->backtrack();
                $this->match(null, true);
                continue;
            }
            if(\is_array($matches)) {
                foreach($matches as $shortcode) {
                    $shortcodes[] = $shortcode;
                }
            }
        }
        ini_set('xdebug.max_nesting_level', $nestingLevel);

        return $shortcodes;
    }
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;
    }
20158
protected function _parseTags(&$text)
    {
        $replace = array();
        $matches = array();

        // <ktml:block extend|prepend|replace="[name]"></khtml:block>
        if(preg_match_all('#<ktml:block\s+(extend|prepend|replace)="([^"]+)"(.*)>(.*)</ktml:block>#siU', $text, $matches))
        {
            $count = count($matches[0]);

            for($i = 0; $i < $count; $i++)
            {
                $name = $matches[2][$i];

                //Create attributes array
                $defaults = array(
                    'title'   => '',
                    'extend'  => ''
                );

                $attributes = array_merge($defaults, $this->parseAttributes($matches[3][$i]));

                //Create block
                $block = array(
                    'content'  => $matches[4][$i],
                    'title'    => $attributes['title'],
                    'extend'   => $matches[1][$i],
                    'attribs'  => (array) array_diff_key($attributes, $defaults)
                );

                //Clear any prior added blocks
                if($block['extend'] == 'replace') {
                    $this->clearBlocks($name);
                }

                $this->addBlock($name, $block);

                //Do not continue adding blocks
                if($block['extend'] == 'replace') {
                    break;
                }
            }

            //Remove the tags
            $text = str_replace($matches[0], '', $text);
        }

        // <ktml:block name="[name]" condition="[condition]"></khtml:block>
        if(preg_match_all('#<ktml:block\s+name="([^"]+)"(.*"[^"]*")?>(.*)</ktml:block>#siU', $text, $matches))
        {
            $count = count($matches[1]);

            for($i = 0; $i < $count; $i++)
            {
                $name = $matches[1][$i];

                if($this->hasBlocks($name))
                {
                    $attribs     = $this->parseAttributes( $matches[2][$i] );
                    $replace[$i] = '';

                    if(isset($attribs['condition']))
                    {
                        if($this->_countBlocks($attribs['condition']))
                        {
                            unset($attribs['condition']);
                            $replace[$i] = $this->_renderBlocks($name, $attribs);
                        }
                    }
                    else $replace[$i] = $this->_renderBlocks($name, $attribs);

                    if(!empty($replace[$i])) {
                        $replace[$i] = str_replace('<ktml:block:content>', $replace[$i], $matches[3][$i]);
                    }
                }
            }

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

        $replace = array();
        $matches = array();
        // <ktml:block name="[name]" condition="[condition]" />
        if(preg_match_all('#<ktml:block\s+name="([^"]+)"(.*"[^"]*")?\s+\/>#siU', $text, $matches))
        {
            $count = count($matches[1]);

            for($i = 0; $i < $count; $i++)
            {
                $name = $matches[1][$i];

                if($this->hasBlocks($name))
                {
                    $attribs     = $this->parseAttributes( $matches[2][$i]);
                    $replace[$i] = '';

                    if(isset($attribs['condition']))
                    {
                        if($this->_countBlocks($attribs['condition']))
                        {
                            unset($attribs['condition']);
                            $replace[$i] = $this->_renderBlocks($name, $attribs);
                        }
                    }
                    else $replace[$i] = $this->_renderBlocks($name, $attribs);

                }
            }

            $text = str_replace($matches[0], $replace, $text);
        }
    }
241589
public static function parseInlineOperator($text)
    {
        $operator_name = 'contains';
        $operator = Arr::get($text, 0, '');
        $value = Arr::get($text, 1, false);

        self::checkInlineOperator($operator, $value);

        if (!empty($operator)) {
            $operator_name = Arr::get(self::getOperator('string', $operator), 'inline', 'contains');
        }

        return [
            $operator_name,
            $operator,
            $value,
        ];
    }
1053146
private function parse_tag(string $text){
		$res = [];
		$text = $this->clear_text($text);
		$tag_end = strpos($text, ' ');
		if ( $tag_end !== false ){
			// Get tag
			$res['tag'] = substr($text, 1, $tag_end - 1);
			if ( in_array($res['tag'], array_keys($this->tags)) ){
        if (
          $this->tag_has_text($res['tag']) &&
          ($text = substr($text, $tag_end + 1))
        ){
          $res['text'] = $this->clear_text($text);
        }
				else {
					// Get type
					if (
            $this->tag_has_type($res['tag']) &&
            ($type = $this->tag_get_type($text)) &&
            !empty($type[1])
          ){
						$res['type'] = $type[1][0];
					}
					// Get default value
					if (
            $this->tag_has_default($res['tag']) &&
            ($def = $this->tag_get_default($text)) &&
            !empty($def[1])
          ){
						$res['default'] = $def[1][0];
					}
					// Get name
					if ( isset($def[1]) ){
						$n = $def[0][1] + strlen($def[0][0]) + 1;
					}
					else if ( isset($type[1]) ){
						$n = $type[0][1] + strlen($type[0][0]) + 1;
					}
					else {
						$n = $tag_end + 1;
					}
					if (
            $this->tag_has_name($res['tag']) &&
						($name = $this->tag_get_name(substr($text, $n)))
					){
						$res['name'] = $this->clear_text($name[0][0]);
					}
					// Get description
					if ( isset($name[0]) ){
						$d = $n + $name[0][1] + strlen($name[0][0]) + 1;
					}
					else if ( isset($type[1]) ){
						$d = $type[0][1] + strlen($type[0][0]) + 1;
					}
          else {
						$d = $tag_end + 1;
					}
					if (
            $this->tag_has_desc($res['tag']) &&
            ($desc = substr($text, $d))
          ){
						$res['description'] = $this->clear_text($desc);
					}
				}

				return $res;
			}
		}
		return false;
	}
514455
public function onStart($text)
    {
        // process of smileys and other special characters
        if ($this->getParam('convertSmileys'))
            $text = Smiley::convertSmileys($text);
        if ($this->getParam('convertSymbols'))
            $text = Smiley::convertSymbols($text);

        // if a specific pre-parse function was defined, it is called
        /** @var callable $func */
        $func = $this->getParam('preParseFunction');
        if (isset($func))
            $text = $func($text);
        return ($text);
    }
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;
    }
738707
protected function parse($text) {
        // Build tree structure
        $in = array();
        for ($ptr=0,$len=strlen($text),$tree=array(),$node=&$tree,
            $stack=array(),$depth=0,$tmp='';$ptr<$len;)
            if (preg_match('/^@(end)?('.$this->tags.')\b(.*)/i', substr($text,$ptr),$match)) {
                $single = substr($match[3], strlen($match[3])-1)==='@';
                !$single || $match[3] = substr($match[3], 0, strlen($match[3])-1);
                if (strlen($tmp))
                    $node[] = $tmp;
                // Element node
                if ($match[1]) {
                    if ($in) {
                        // in element
                        for ($i=count($in)-1; $i > -1 ; --$i)
                            $in[$i][1] = array_pop($node);
                        $node['@in'] = $in;
                        $in = array();
                    }
                    // Find matching start tag
                    $save  = $depth;
                    $found = false;
                    while ($depth>0) {
                        $depth--;
                        foreach ($stack[$depth] as $item)
                            if (is_array($item) && isset($item[$match[2]])) {
                                // Start tag found
                                $found = true;
                                break 2;
                            }
                    }
                    if (!$found)
                        // Unbalanced tag
                        $depth = $save;
                    $node =& $stack[$depth];
                }
                elseif ($this->intag($match[2])) {
                    $in[] = array($match[2], '@attrib'=>$this->parseAttrib($match[3]), '');
                }
                else {
                    // Start tag
                    $stack[$depth]   =& $node;
                    $node            =& $node[][$match[2]];
                    $node['@attrib'] = $this->parseAttrib($match[3]);
                    if ($single)
                        // single
                        $node =& $stack[$depth];
                    else
                        $depth++;
                }
                $tmp = '';
                $ptr += strlen($match[0]);
            }
            else {
                // Text node
                $tmp .= substr($text,$ptr,1);
                $ptr++;
            }
        if (strlen($tmp))
            // Append trailing text
            $node[] = $tmp;
        // Break references
        unset($node, $stack);

        return $tree;
    }