Get the open and closing PHP tag tokens from the given string.

@param  string  $contents
@return \Illuminate\Support\Collection
558236
protected function getOpenAndClosingPhpTokens($contents)
    {
        return collect(token_get_all($contents))
            ->pluck($tokenNumber = 0)
            ->filter(function ($token) {
                return in_array($token, [T_OPEN_TAG, T_OPEN_TAG_WITH_ECHO, T_CLOSE_TAG]);
            });
    }
43642
public function parse($content)
    {
        $tokens = $this->getTokens($content);

        $i = 0;
        $result = array();
        $currentMachine = '';

        while ($i < count($tokens)) {
            $currentToken = $tokens[$i];
            if ($currentToken == 'machine') {
                if (!isset($tokens[$i+1])) {
                    throw new ParseException("Cannot fetch machine name");
                }
                $currentMachine = $tokens[$i+1];
                $result[$currentMachine] = array();
                $i+=2;
            } else if ($currentToken == 'default') {
                $currentMachine = 'default';
                $result[$currentMachine] = array();
                $i++;
            } else {
                if (!in_array($currentToken, static::$netrcKeys)) {
                    throw new ParseException("Cannot handle unknown key '$currentToken' for '$currentMachine' machine");
                }
                if (!isset($tokens[$i+1])) {
                    throw new ParseException("Cannot fetch value of '$tokens[$i]' key for '$currentMachine' machine");
                }
                if (!$currentMachine) {
                    throw new ParseException("Cannot handle key '$currentToken' for unset machine");
                }
                $result[$currentMachine][$currentToken] = $tokens[$i+1];
                $i+=2;
            }
        }

        return $result;
    }
440606
public function parse($content)
    {
        $this->parser
            ->setSafeMode(config('markdown.safe-mode', false))
            ->setUrlsLinked(config('markdown.urls', true))
            ->setMarkupEscaped(config('markdown.markups', true));

        if (config('markdown.xss', true)) {
            $content = preg_replace('/(\[.*\])\(javascript:.*\)/', '$1(#)', $content);
        }

        return $this->parser->text($content);
    }
1091668
public static function getArrayKeys($content)
    {
        preg_match_all(self::ARRAY_KEYS_REGEX, trim($content), $matches);

        return !empty($matches) ? $matches[1] : array();
    }
1116047
private static function extractClasses($contents, $extraTypes)
    {
        // strip heredocs/nowdocs
        $contents = preg_replace(
            '{<<<\s*(\'?)(\w+)\\1(?:\r\n|\n|\r)(?:.*?)(?:\r\n|\n|\r)\\2(?=\r\n|\n|\r|;)}s',
            'null',
            $contents
        );
        // strip strings
        $contents = preg_replace(
            '{"[^"\\\\]*+(\\\\.[^"\\\\]*+)*+"|\'[^\'\\\\]*+(\\\\.[^\'\\\\]*+)*+\'}s',
            'null',
            $contents
        );
        // strip leading non-php code if needed
        if (substr($contents, 0, 2) !== '<?') {
            $contents = preg_replace('{^.+?<\?}s', '<?', $contents, 1, $replacements);
            if ($replacements === 0) {
                return array();
            }
        }
        // strip non-php blocks in the file
        $contents = preg_replace('{\?>.+<\?}s', '?><?', $contents);
        // strip trailing non-php code if needed
        $pos = strrpos($contents, '?>');
        if (false !== $pos && false === strpos(substr($contents, $pos), '<?')) {
            $contents = substr($contents, 0, $pos);
        }

        preg_match_all(
            '{
            (?:
                 \b(?<![\$:>])(?P<type>class|interface' . $extraTypes .
            ') \s+ (?P<name>[a-zA-Z_\x7f-\xff:][a-zA-Z0-9_\x7f-\xff:\-]*)
               | \b(?<![\$:>])(?P<ns>namespace) (?P<nsname>\s+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*' .
            '(?:\s*\\\\\s*[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*)? \s*[\{;]
            )
        }ix',
            $contents,
            $matches
        );

        return $matches;
    }
945637
public function open( $attributes = array() ) {
        $this->setAttributes( $attributes );
        $html = '<' . $this->tagName
                    . $this->renderAttributes()
                    ;
        // should we close it ?
        if( $this->closeEmpty || $this->hasChildren() ) {
            $html .= '>';
        } else {
            $html .= '/>';
        }
        return $html;
    }
674502
private function recursivelyStringify($content = null)
        {
            $return = [];
            if (false === $content || null === $content) {
                return;
            } else if (!is_array($content)) {
                $return[] = $content;
            } else {
                foreach ($content as $element) {
                    $return[] = $this->recursivelyStringify($element);
                }
            }
            return implode('', $return);
        }
207524
private function getTokens($content)
    {
        // fetch non-empty lines
        $lines = preg_split('/\r\n|\r|\n/', $content, -1, PREG_SPLIT_NO_EMPTY);
        $tokens = array();
        foreach ($lines as $line) {
            // throwing tokens after '#' sign
            $commentCharPosition = strpos($line, "#");
            $lineWithoutComments = ($commentCharPosition === false) ? $line : substr($line, 0, strpos($line, "#"));
            // storing current line tokens
            if ($lineWithoutComments) {
                $tokens = array_merge($tokens, preg_split('/\s+/', $lineWithoutComments, -1, PREG_SPLIT_NO_EMPTY));
            }
        }
        return $tokens;
    }
865210
public function enterToken(array $token, $content)
    {
        switch ($token[Lexer::TYPE]) {
            case Lexer::T_FUNC_CLOSE:
                return $this->parent;

            case Lexer::T_LABEL:
                $this->currentLabel = trim(substr(trim($token[Lexer::VALUE]), 0, -1));
                break;

            case Lexer::T_QUOTED_STRING:
            case Lexer::T_NUMBER:
            case Lexer::T_TRUE:
            case Lexer::T_FALSE:
            case Lexer::T_NULL:
                $value = $this->getValueOfToken($token);
                $this->addParam($value, $token);
                break;

            case Lexer::T_ARRAY_OPEN:
                $array = new ArrayContext($token, $this);
                $this->addParam($array, $token);

                return $array;
                break;

            case Lexer::T_FUNC_OPEN:
                $func = new FuncContext($token, $this);
                $this->addParam($func, $token);

                return $func;

            case Lexer::T_COMMA:
                break;

            default:
                return null;
        }

        return $this;
    }
219002
public function parse($contents, $includeDefaults = false)
    {
        $old_libxml_error = libxml_use_internal_errors(true);
        
        $dom = new DOMDocument;
        
        if(@$dom->loadHTML($contents) === false) {
            throw new RuntimeException("Contents is empty");
        }
        
        libxml_use_internal_errors($old_libxml_error);

        foreach($dom->getElementsByTagName('meta') as $tag) {
            if($includeDefaults && $tag->hasAttribute('name') && $tag->hasAttribute('content') && $tag->getAttribute('name') == 'description') {
                $this->addMeta('non-og-description', $tag->getAttribute('content'), self::APPEND);
            } else if($tag->hasAttribute('property') && $tag->hasAttribute('content')) {
                $this->addMeta($tag->getAttribute('property'), $tag->getAttribute('content'), self::APPEND);
            }
        }

        if($includeDefaults) {
            $titles = $dom->getElementsByTagName('title');
            if ($titles->length > 0) {
                $this->addMeta('non-og-title', $titles->item(0)->textContent, self::APPEND);
            }
        }

        unset($dom);
        
        return $this;
    }
669724
public static function getHtmlTags($content, $closeTags = true)
    {
        if ($closeTags == true) {
            $re = '@<[^>]*>@';
        } else {
            $re = '@<[^>/]*>@';
        }

        preg_match_all($re, $content, $matches, PREG_SET_ORDER, 0);

        if (isset($matches) && !empty($matches)) {
            $tags = array();
            foreach ($matches as $match) {
                $tags[] = $match[0];
            }

            $tags = array_unique($tags);

            return $tags;
        }

        return;
    }
982089
protected function parse($content)
    {
        $result = array();
        foreach ($this->parsers as $parser) {
            $nodes = $parser->getNodes($content);
            if (!$nodes) {
                continue;
            }

            foreach ($nodes as $node) {
                $result[] = $node;
            }
        }

        return $result;
    }
1049739
protected function preprocessWindowsPaths($contents)
    {
        $expression = "/'([A-Za-z]:)?((\\\\|\/)[^\\/:*?\"\'<>|\r\n]*)*'/";

        $paths = array();
        preg_match_all($expression, $contents, $paths);

        $modified = $contents;
        foreach ($paths[0] as $path) {
            $normalizedPath = str_replace('\\\\', '/', $path);
            $modified = str_replace($path, $normalizedPath, $modified);
        }

        if ($contents !== $modified) {
            $this->myCommand->info('Preprocessed windows paths in "bootstrap/cache/config.php".');
        }

        return $modified;
    }
84244
protected function _extractChunks($string) {
        $strPos = 0;
        $strLength = mb_strlen($string);
        $openBracket = $this->getConfig('open');
        $closeBracket = $this->getConfig('close');
        $hasList = isset($this->_filters['List']);
        $starOpen = false;
        $chunks = array();

        while ($strPos < $strLength) {
            $tag = array();
            $possibleLiteral = false;
            $isLiteral = false;

            // Find opening tag
            $openPos = mb_strpos($string, $openBracket, $strPos);

            if ($openPos === false) {
                $openPos = $strLength;
            }

            if ($openPos + 1 > $strLength) {
                $nextOpenPos = $strLength;
            } else {
                $nextOpenPos = mb_strpos($string, $openBracket, $openPos + 1);

                if ($nextOpenPos === false) {
                    $nextOpenPos = $strLength;
                }

                $possibleLiteral = ($openPos + 1 === $nextOpenPos);
            }

            // Find closing tag
            $closePos = mb_strpos($string, $closeBracket, $strPos);

            if ($closePos === false) {
                $closePos = $strLength + 1;
            }

            if ($possibleLiteral) {
                $isLiteral = (isset($string[$closePos + 1]) && $string[$closePos + 1] === $closeBracket);
            }

            // Literal tag found, do not parse
            if ($isLiteral) {
                $newPos = $closePos + 2;

                $tag['text'] = mb_substr($string, $openPos + 1, ($closePos - $openPos));
                $tag['type'] = self::TAG_NONE;

            // Possible tag found, lets look
            } else if ($openPos === $strPos) {

                // Child open tag before closing tag
                if ($nextOpenPos < $closePos) {
                    $newPos = $nextOpenPos;
                    $tag['text'] = mb_substr($string, $strPos, ($nextOpenPos - $strPos));
                    $tag['type'] = self::TAG_NONE;

                // Tag?
                } else {
                    $newPos = $closePos + 1;
                    $newTag = $this->_buildTag(mb_substr($string, $strPos, (($closePos - $strPos) + 1)));

                    // Valid tag
                    if ($newTag) {
                        $tag = $newTag;

                        // Special handling for star list items
                        if ($hasList) {
                            if ($tag['type'] === self::TAG_OPEN) {

                                // A new star item opened
                                if ($tag['tag'] === '*' && !$starOpen) {
                                    $starOpen = true;

                                // Another star item appeared, so close the previous
                                } else if ($starOpen && $tag['tag'] === '*') {
                                    $chunks[] = array(
                                        'tag' => '*',
                                        'type' => self::TAG_CLOSE,
                                        'text' => '[/*]',
                                        'attributes' => array()
                                    );
                                }

                            } else if ($tag['type'] === self::TAG_CLOSE) {
                                if ($starOpen && in_array($tag['tag'], array('list', 'olist', 'ol', 'ul'))) {
                                    $starOpen = false;

                                    $chunks[] = array(
                                        'tag' => '*',
                                        'type' => self::TAG_CLOSE,
                                        'text' => '[/*]',
                                        'attributes' => array()
                                    );
                                } else if ($tag['tag'] === '*') {
                                    $starOpen = false;
                                }
                            }
                        }

                    // Not a valid tag
                    } else {
                        $tag['text'] = mb_substr($string, $strPos, $closePos - $strPos + 1);
                        $tag['type'] = self::TAG_NONE;
                    }
                }

            // No tag, just text
            } else {
                $newPos = $openPos;

                $tag['text'] = mb_substr($string, $strPos, ($openPos - $strPos));
                $tag['type'] = self::TAG_NONE;
            }

            // Join consecutive text elements
            if ($tag['type'] === self::TAG_NONE && isset($prev) && $prev['type'] === self::TAG_NONE) {
                $tag['text'] = $prev['text'] . $tag['text'];
                array_pop($chunks);
            }

            $chunks[] = $tag;
            $prev = $tag;
            $strPos = $newPos;
        }

        $this->_nodes = $this->_extractNodes($chunks);

        return $this->_nodes;
    }
1005855
public static function markupToPHP($content) 
    {
        if ($content instanceof phpQueryObject) {
            $content = $content->markupOuter();
        }
        /* <php>...</php> to <?php...? > */
        $content = preg_replace_callback(
            '@<php>\s*<!--(.*?)-->\s*</php>@s',
            //            create_function('$m',
            //                'return "<'.'?php ".htmlspecialchars_decode($m[1])." ?'.'>";'
            //            ),
            array('phpQuery', '_markupToPHPCallback'),
            $content
        );
        /* <node attr='< ?php ? >'> extra space added to save highlighters */
        $regexes = array(
        '@(<(?!\\?)(?:[^>]|\\?>)+\\w+\\s*=\\s*)(\')([^\']*)(?:&lt;|%3C)\\?(?:php)?(.*?)(?:\\?(?:&gt;|%3E))([^\']*)\'@s',
        '@(<(?!\\?)(?:[^>]|\\?>)+\\w+\\s*=\\s*)(")([^"]*)(?:&lt;|%3C)\\?(?:php)?(.*?)(?:\\?(?:&gt;|%3E))([^"]*)"@s',
        );
        foreach($regexes as $regex) {
            while (preg_match($regex, $content)) {
                $content = preg_replace_callback(
                    $regex,
                    create_function(
                        '$m',
                        'return $m[1].$m[2].$m[3]."<?php "
							.str_replace(
								array("%20", "%3E", "%09", "&#10;", "&#9;", "%7B", "%24", "%7D", "%22", "%5B", "%5D"),
								array(" ", ">", "	", "\n", "	", "{", "$", "}", \'"\', "[", "]"),
								htmlspecialchars_decode($m[4])
							)
							." ?>".$m[5].$m[2];'
                    ),
                    $content
                );
            }
        }
        return $content;
    }
1156807
public function parseLang($content) {
        $this->_content = $content;
        $this->_parseDebugStart();
        $this->_parsePath();
        $this->_parseGravatar();
        $this->_parseUrl();
        $this->_parsePhp();
        $this->_parseLang();
        $this->_parseForeach();
        $this->_parseFor();
        $this->_parseVar();
        $this->_parseVarFunc();
        $this->_parseCondition();
        $this->_parseFunction();
        $this->_parseException();
        $this->_parseDebugEnd();

        return $this->_content;
    }
125693
public function tagEmpty($tag, $content)
    {
        $name     = $tag['name'];
        $name     = $this->autoBuildVar($name);
        $parseStr = '<?php if(empty(' . $name . ') || ((' . $name . ' instanceof \think\Collection || ' . $name . ' instanceof \think\Paginator ) && ' . $name . '->isEmpty())): ?>' . $content . '<?php endif; ?>';

        return $parseStr;
    }