Parses headers from string
@param  string $str
@return array
481455
private function getHeaders($str) {
    $str = explode(self::LE . self::LE, $str);
    $str = reset($str);
    $str = explode(self::LE, $str);
    $new = array();
    $s = 1;
    foreach ($str as $line) {
      $pos = strpos($line, ': ');
      if ($pos !== false) {
        $key = strtolower(substr($line, 0, $pos));
        if (!isset($new[$key])) {
          $new[$key] = preg_replace('/\s+/', ' ', trim(substr($line, $pos+1)));
        }
        else {
          $new[$key.'-'.$s] = preg_replace('/\s+/', ' ', trim(substr($line, $pos+1)));
          $s++;
        }
      }
      else {
        $new['status'] = $line; # HTTP/1.1 200 OK
      }
    }
    return $new;
  }
821240
public static function extract($str)
    {
        preg_match_all("/(^|[\n ])#([a-z0-9_-]*)/is", $str, $matches);

        if (!is_array($matches) || !count($matches)) {
            return [];
        }

        $hashtags = [];
        foreach ($matches[0] as $match) {
            $match = ltrim(trim($match), '#_ ');
            if (self::isValid($match)) {
                $hashtags[strtolower($match)] = $match;
            }
        }

        return array_values($hashtags);
    }
1346646
protected function parse($str)
    {
        $count = preg_match_all($this->tags->regex(), $str, $matches);

        // If we didn't find anything, return the string right back
        if (!$count || !is_array($matches)) {
            return $str;
        }

        // All we want is the array of actual strings matched
        $matches = reset($matches);

        return $this->parseTags($str, $matches);
    }
170971
public static function get(string $str):array
    {
        $str = trim($str);
        $strArr = Str::toArray($str);
        $results = [];
        foreach ($strArr as $s) {
            $results[] = self::getSingle($s);
        }
        return $results;
    }
1337987
protected function parseResponseHeadersAsArray($headers)
    {
        if (empty($headers)) return [];

        $headersArray = [];

        foreach (preg_split('#[\r\n]+#', $headers) as $headerString) {

            if ( ! preg_match('#^\s*(?<name>.*?)\s*:\s*(?<value>.*)\s*$#', $headerString, $matches)) continue;

            $headersArray[ $matches['name'] ] = $matches['value'];
        }

        return $headersArray;
    }
1292636
protected function extractReference(/*# string */ $str)/*# : array */
    {
        $res = [];
        if (preg_match_all(
            $this->getPattern(),
            $str,
            $matched,
            \PREG_SET_ORDER
        )) {
            foreach ($matched as $m) {
                $res[$m[1]] = $m[2];
            }
            return $res;
        }
        return $res;
    }
550025
private function parseLine($str, $color = null)
    {
        $parsed = [];
        $lines = explode(PHP_EOL, $str);
        $last = count($lines) - 1;
        foreach ($lines as $key => $line) {
            $parsed[] = [
                'colored' => $color ? sprintf("\033[%sm%s\033[0m", $color, $line) : $line,
                'original' => $line,
                'newline' => $key < $last
            ];
        }

        return $parsed;
    }
1209233
public function parseStringMetadata($str)
    {
        $info = array();
        if (0!==preg_match('~^\[([^\]]+)\]~i', $str, $matches)) {
            $str = str_replace($matches[0], '', $str);
            $types = $matches[1];
            $types_items = explode(';', $types);
            foreach ($types_items as $item) {
                $parts = explode(':', $item);
                if (count($parts)>1) {
                    $info[$parts[0]] = $parts[1];
                } else {
                    $info[] = $parts[0];
                }
            }
        }
        return array($str, $info);
    }
1353356
protected function parse($str)
    {
        $pos = 0;
        $len = strlen($str);

        // Convert infix operators to postfix using the shunting-yard algorithm.
        $output = array();
        $stack = array();
        while ($pos < $len) {
            $next = substr($str, $pos, 1);

            switch ($next) {
                // Ignore whitespace
                case ' ':
                case "\t":
                    $pos++;
                    break;

                // Variable (n)
                case 'n':
                    $output[] = array('var');
                    $pos++;
                    break;

                // Parentheses
                case '(':
                    $stack[] = $next;
                    $pos++;
                    break;

                case ')':
                    $found = false;
                    while (!empty($stack)) {
                        $o2 = $stack[count($stack) - 1];
                        if ($o2 !== '(') {
                            $output[] = array('op', array_pop($stack));
                            continue;
                        }

                        // Discard open paren.
                        array_pop($stack);
                        $found = true;
                        break;
                    }

                    if (!$found) {
                        throw new Exception('Mismatched parentheses');
                    }

                    $pos++;
                    break;

                // Operators
                case '|':
                case '&':
                case '>':
                case '<':
                case '!':
                case '=':
                case '%':
                case '?':
                    $end_operator = strspn($str, self::OP_CHARS, $pos);
                    $operator = substr($str, $pos, $end_operator);
                    if (!array_key_exists($operator, self::$op_precedence)) {
                        throw new Exception(sprintf('Unknown operator "%s"', $operator));
                    }

                    while (!empty($stack)) {
                        $o2 = $stack[count($stack) - 1];

                        // Ternary is right-associative in C
                        if ($operator === '?:' || $operator === '?') {
                            if (self::$op_precedence[$operator] >= self::$op_precedence[$o2]) {
                                break;
                            }
                        } elseif (self::$op_precedence[$operator] > self::$op_precedence[$o2]) {
                            break;
                        }

                        $output[] = array('op', array_pop($stack));
                    }
                    $stack[] = $operator;

                    $pos += $end_operator;
                    break;

                // Ternary "else"
                case ':':
                    $found = false;
                    $s_pos = count($stack) - 1;
                    while ($s_pos >= 0) {
                        $o2 = $stack[$s_pos];
                        if ($o2 !== '?') {
                            $output[] = array('op', array_pop($stack));
                            $s_pos--;
                            continue;
                        }

                        // Replace.
                        $stack[$s_pos] = '?:';
                        $found = true;
                        break;
                    }

                    if (!$found) {
                        throw new Exception('Missing starting "?" ternary operator');
                    }
                    $pos++;
                    break;

                // Default - number or invalid
                default:
                    if ($next >= '0' && $next <= '9') {
                        $span = strspn($str, self::NUM_CHARS, $pos);
                        $output[] = array('value', intval(substr($str, $pos, $span)));
                        $pos += $span;
                        break;
                    }

                    throw new Exception(sprintf('Unknown symbol "%s"', $next));
            }
        }

        while (!empty($stack)) {
            $o2 = array_pop($stack);
            if ($o2 === '(' || $o2 === ')') {
                throw new Exception('Mismatched parentheses');
            }

            $output[] = array('op', $o2);
        }

        $this->tokens = $output;
    }
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;
	}
169592
protected static function parseAs($str, $alias1 = null) {
        $table = preg_split('#\b(as|\s+)\b#i', trim($str));
        if (count($table) == 1) {
            $name  = $table [0];
            $alias = $alias1;
        } else {
            $name  = $table [0];
            $alias = trim(array_pop($table));
        }

        return [trim($name), trim($alias)];
    }
582302
public static function parseHeaderValue(string $value): array
    {
        $parts = \explode(';', $value);
        $type = \trim($parts[0]);
        unset($parts[0]);

        $parameters = [];
        foreach ($parts as $part) {
            [$k, $v] = \explode('=', $part, 2);

            $key = \strtolower(\trim($k));
            $parameters[$key] = \trim($v, ' "');
        }

        return [$type, $parameters];
    }
621033
public static function extractHeaders($response_str)
    {
        $headers = array();

        // First, split body and headers
        $parts = preg_split('|(?:\r?\n){2}|m', $response_str, 2);
        if (! $parts[0]) return $headers;

        // Split headers part to lines
        $lines = explode("\n", $parts[0]);
        unset($parts);
        $last_header = null;

        foreach($lines as $line) {
            $line = trim($line, "\r\n");
            if ($line == "") break;

            // Locate headers like 'Location: ...' and 'Location:...' (note the missing space)
            if (preg_match("|^([\w-]+):\s*(.+)|", $line, $m)) {
                unset($last_header);
                $h_name = strtolower($m[1]);
                $h_value = $m[2];

                if (isset($headers[$h_name])) {
                    if (! is_array($headers[$h_name])) {
                        $headers[$h_name] = array($headers[$h_name]);
                    }

                    $headers[$h_name][] = $h_value;
                } else {
                    $headers[$h_name] = $h_value;
                }
                $last_header = $h_name;
            } elseif (preg_match("|^\s+(.+)$|", $line, $m) && $last_header !== null) {
                if (is_array($headers[$last_header])) {
                    end($headers[$last_header]);
                    $last_header_key = key($headers[$last_header]);
                    $headers[$last_header][$last_header_key] .= $m[1];
                } else {
                    $headers[$last_header] .= $m[1];
                }
            }
        }

        return $headers;
    }
118498
public static function parseHeaders($headerstr=false) {
        if ( $headerstr === false ) $headerstr = self::getLastHeadersReceived();
        $lines = explode("\n",$headerstr);
        $headermap = array();

        foreach ($lines as $line) {
            $pos = strpos($line, ':');
            if ( $pos < 1 ) continue;
            $key = substr($line,0,$pos);
            $value = trim(substr($line, $pos+1));
            if ( strlen($key) < 1 || strlen($value) < 1 ) continue;
            $headermap[$key] = $value;
        }
        return $headermap;
    }
110517
public function parse(string $str): Includes
    {
        // Ignore whitespace
        $str = preg_replace('/\s/', '', $str);

        if (empty($str)) {
            return new Includes();
        }

        // Parse a string in the following format:
        // pets{id,name,owner{id,name},photos:limit(3)}:limit(5):offset(10)

        // Define the current parse state
        $state = [
            // Original string
            'string' => $str,
            // Position in string
            'pos' => 0,
            // Length of the original string being processed
            'len' => 0,
            // Current character being processed
            'char' => null,
            // The accumulated current key for the field
            'buffer' => '',
            // The current parent keys
            'parent' => [],
            // Previous parent
            'prevParent' => null,
            // Our list of keys
            'keys' => [],
            // Our list of params
            'params' => [],
        ];

        // Process each character, moving through the state and build
        while ($state['pos'] < ($len = \strlen($str))) {
            $state['char'] = $str[$state['pos']];
            $state['len'] = $len;

            switch ($state['char']) {
                case '{':
                    // Begin children
                    if (!empty($state['buffer'])) {
                        $state['keys'][] = $this->prefixParentKeys($state['buffer'], $state['parent']);
                        $state['parent'][] = $state['buffer'];
                        $state['buffer'] = '';
                    }
                    break;
                case ',':
                    // Delimiter
                    if (!empty($state['buffer'])) {
                        $state['keys'][] = $this->prefixParentKeys($state['buffer'], $state['parent']);
                        $state['buffer'] = '';
                    }
                    break;
                case '}':
                    // End children
                    if (!empty($state['buffer'])) {
                        $state['keys'][] = $this->prefixParentKeys($state['buffer'], $state['parent']);
                        $state['buffer'] = '';
                    }
                    if (!empty($state['parent'])) {
                        $state['prevParent'] = $state['parent'];
                        array_pop($state['parent']);
                    }
                    break;
                case ':':
                    // Looks like it's a parameter. Eg. :limit(10)
                    // Well, if we have a buffer, then that's our parent, if we don't
                    // we will use the parent we saved when we popped the last parent state.
                    $parentKey = !empty($state['buffer']) ?
                        $this->prefixParentKeys($state['buffer'], $state['parent']) : $this->flattenKeys($state['prevParent']);

                    if (preg_match('/^:(\w+)\(([^)]+)\)/', substr($str, $state['pos']), $match)) {
                        // We have a match
                        list($param, $key, $val) = $match;
                        $len = \strlen($param);

                        // Initialise the parent key in our params associative array
                        if (!isset($state['params'][$parentKey])) {
                            $state['params'][$parentKey] = [];
                        }

                        // Store the param key and value
                        $state['params'][$parentKey][$key] = $val;

                        // Chop our parameter out of the original string
                        $str =
                            substr($str, 0, $state['pos']).
                            substr($str, $state['pos'] + $len);

                        // We need to move the position head back one after the chop
                        // since it will be advanced at the end of the loop
                        $state['pos']--;
                    }
                    break;
                default:
                    // Any other character should just be appended
                    $state['buffer'] .= $state['char'];
                    break;
            }
            $state['pos']++;
        }

        // Finally handle any non-empty buffer
        if (!empty($state['buffer'])) {
            $state['keys'][] = $this->prefixParentKeys($state['buffer'], $state['parent']);
            $state['buffer'] = '';
        }

        return (new Includes())
            ->set($state['keys'])
            ->setParams($state['params']);
    }
288211
private function parseHeader($header)
    {
        $res = preg_match_all('/(?:[^,"]*+(?:"[^"]*+")?)+[^,"]*+/', $header, $matches);

        if (!$res) {
            throw new InvalidHeader(sprintf('Failed to parse accept header: "%s"', $header));
        }

        return array_values(array_filter(array_map('trim', $matches[0])));
    }
1260342
protected function parseHeaders($input)
    {
        if ($input !== '') {
            // Unfold the input
            $input   = preg_replace('/' . $this->params['crlf'] . "(\t| )/", ' ', $input);
            $headers = explode($this->params['crlf'], trim($input));

            foreach ($headers as $value) {
                $hdr_name  = substr($value, 0, $pos = strpos($value, ':'));
                $hdr_value = substr($value, $pos+1);

                if ($hdr_value[0] == ' ') {
                    $hdr_value = substr($hdr_value, 1);
                }

                $return[] = array(
                    'name'  => $hdr_name,
                    'value' => $this->params['decode_headers'] ? $this->decodeHeader($hdr_value) : $hdr_value,
                );
            }
        }
        else {
            $return = array();
        }

        return $return;
    }