Parse URLs from string
@param  string $str
@param  string $rule substitution rule, for example: <a href="[url]">[caption]</a>
@return string
14643
public function urlParser($str, $rule)
    {
        $linkify = new Linkify(['callback' => function ($url, $caption, $isEmail) use ($rule) {
            $rule = str_replace('[url]', $url, $rule);
            $rule = str_replace('[caption]', $caption, $rule);
            return $rule;
        }]);

        return $linkify->process($str);
    }
1166296
public static function fromString(string $str): self
    {
        $rdns = array();
        foreach (DNParser::parseString($str) as $nameComponent) {
            $attribs = array();
            foreach ($nameComponent as list($name, $val)) {
                $type = AttributeType::fromName($name);
                // hexstrings are parsed to ASN.1 elements
                if ($val instanceof Element) {
                    $el = $val;
                } else {
                    $el = AttributeType::asn1StringForType($type->oid(), $val);
                }
                $value = AttributeValue::fromASN1ByOID($type->oid(),
                    $el->asUnspecified());
                $attribs[] = new AttributeTypeAndValue($type, $value);
            }
            $rdns[] = new RDN(...$attribs);
        }
        return new self(...$rdns);
    }
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;
    }
110946
public function parse($str)
	{
		if ($this->isQuoteHtml() === true)
		{
			$str = htmlspecialchars($str, ENT_QUOTES);
		}

		foreach ($this->getBbCodes() as $key => $val)
		{
			$str = preg_replace($key, $val, $str);
		}

		return $str;
	}
835641
static public function fromCamel($str) {
      $str[0] = strtolower($str[0]);
      return preg_replace_callback('/([A-Z])/', function($char) {return "_" . strtolower($char[1]);}, $str);
  }
777806
function fastparse (str) {
  if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) {
    return parse(str)
  }

  var pathname = str
  var query = null
  var search = null

  // This takes the regexp from https://github.com/joyent/node/pull/7878
  // Which is /^(\/[^?#\s]*)(\?[^#\s]*)?$/
  // And unrolls it into a for loop
  for (var i = 1; i < str.length; i++) {
    switch (str.charCodeAt(i)) {
      case 0x3f: /* ?  */
        if (search === null) {
          pathname = str.substring(0, i)
          query = str.substring(i + 1)
          search = str.substring(i)
        }
        break
      case 0x09: /* \t */
      case 0x0a: /* \n */
      case 0x0c: /* \f */
      case 0x0d: /* \r */
      case 0x20: /*    */
      case 0x23: /* #  */
      case 0xa0:
      case 0xfeff:
        return parse(str)
    }
  }

  var url = Url !== undefined
    ? new Url()
    : {}

  url.path = str
  url.href = str
  url.pathname = pathname

  if (search !== null) {
    url.query = query
    url.search = search
  }

  return url
}
264573
function parse($str) {
		preg_match_all('/(\w+|\*)\h*=\h*(?:\[(.+?)\]|(.+?))(?=,|$)/',
			$str,$pairs,PREG_SET_ORDER);
		$out=[];
		foreach ($pairs as $pair)
			if ($pair[2]) {
				$out[$pair[1]]=[];
				foreach (explode(',',$pair[2]) as $val)
					array_push($out[$pair[1]],$val);
			}
			else
				$out[$pair[1]]=trim($pair[3]);
		return $out;
	}
1342973
protected function _replaceUrlValLinks($file, $str)
    {
        $str = preg_replace_callback('#((?:\s+|_)url\s*[:=]\s*[\"\'])([\w-/:.]+)#', function ($match) use ($file) {
            return $match[1] . $this->_completeRelativeLinks($file, $match[2]);
        }, $str);

        $str = preg_replace_callback('#([._]href\s*=\s*["\'])([\w-/:.]+)#', function ($match) use ($file) {
            return $match[1] . $this->_completeRelativeLinks($file, $match[2]);
        }, $str);

        return $str;
    }
833301
public function loadStr(string $str, array $option = []): Dom
    {
        $this->options = new Options;
        $this->options->setOptions($this->globalOptions)
                      ->setOptions($option);

        $this->rawSize = strlen($str);
        $this->raw     = $str;

        $html = $this->clean($str);

        $this->size    = strlen($str);
        $this->content = new Content($html);

        $this->parse();
        $this->detectCharset();

        return $this;
    }
596945
public function parse($value, $rule) {
        $rs = strval($this->filterByStrLen(strval($value), $rule));

        $this->filterByRegex($rs, $rule);

        return $rs;
    }
1053397
public function parse($value, $rule) {
        $rs = $value;

        if (!is_array($rs)) {
            $ruleFormat = !empty($rule['format']) ? strtolower($rule['format']) : '';
            if ($ruleFormat == 'explode') {
                $rs = explode(isset($rule['separator']) ? $rule['separator'] : ',', $rs);
            } else if ($ruleFormat == 'json') {
                $rs = json_decode($rs, TRUE);

                if (!empty($value) && $rs === NULL) {
                    $message = isset($rule['message']) 
                        ? \PhalApi\T($rule['message']) 
                        : \PhalApi\T('{name} illegal json data', array('name' => $rule['name']));
                    throw new BadRequestException($message);
                }
            } else {
                $rs = array($rs);
            }
        }

        $this->filterByRange(count($rs), $rule);

        return $rs;
    }
1009332
protected function _li($str) {
		// Initialize list parser
		$len=strlen($str);
		$ptr=0;
		$dst='';
		$first=TRUE;
		$tight=TRUE;
		$type='ul';
		// Main loop
		while ($ptr<$len) {
			if (preg_match('/^\h*[*-](?:\h?[*-]){2,}(?:\n+|$)/',
				substr($str,$ptr),$match)) {
				$ptr+=strlen($match[0]);
				// Embedded horizontal rule
				return (strlen($dst)?
					('<'.$type.'>'."\n".$dst.'</'.$type.'>'."\n\n"):'').
					'<hr />'."\n\n".$this->build(substr($str,$ptr));
			}
			elseif (preg_match('/(?<=^|\n)([*+-]|\d+\.)\h'.
				'(.+?(?:\n+|$))((?:(?: {4}|\t)+.+?(?:\n+|$))*)/s',
				substr($str,$ptr),$match)) {
				$match[3]=preg_replace('/(?<=^|\n)(?: {4}|\t)/','',$match[3]);
				$found=FALSE;
				foreach (array_slice($this->blocks,0,-1) as $regex)
					if (preg_match($regex,$match[3])) {
						$found=TRUE;
						break;
					}
				// List
				if ($first) {
					// First pass
					if (is_numeric($match[1]))
						$type='ol';
					if (preg_match('/\n{2,}$/',$match[2].
						($found?'':$match[3])))
						// Loose structure; Use paragraphs
						$tight=FALSE;
					$first=FALSE;
				}
				// Strip leading whitespaces
				$ptr+=strlen($match[0]);
				$tmp=$this->snip($match[2].$match[3]);
				if ($tight) {
					if ($found)
						$tmp=$match[2].$this->build($this->snip($match[3]));
				}
				else
					$tmp=$this->build($tmp);
				$dst.='<li>'.$this->scan(trim($tmp)).'</li>'."\n";
			}
		}
		return strlen($dst)?
			('<'.$type.'>'."\n".$dst.'</'.$type.'>'."\n\n"):'';
	}
1174551
public function loadTemplateFromString($str)
    {
        $this->source = 'string: '.$str;
        $this->template = $this->tags = [];
        if (!$str) {
            return;
        }
        $this->tag_cnt = [];

        /* First expand self-closing tags {$tag} -> {tag}{/tag} */
        $str = preg_replace('/{\$([-_:\w]+)}/', '{\1}{/\1}', $str);

        $this->parseTemplate($str);

        return $this;
    }
267510
public static function load($str)
    {
        $dom       = new Dom;
        self::$dom = $dom;

        return $dom->load($str);
    }
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;
    }
931584
function _filter_uri($str)
	{
		if ($str != '' && $this->config->item('permitted_uri_chars') != '' && $this->config->item('enable_query_strings') == FALSE)
		{
			// preg_quote() in PHP 5.3 escapes -, so the str_replace() and addition of - to preg_quote() is to maintain backwards
			// compatibility as many are unaware of how characters in the permitted_uri_chars will be parsed as a regex pattern
			if ( ! preg_match("|^[".str_replace(array('\\-', '\-'), '-', preg_quote($this->config->item('permitted_uri_chars'), '-'))."]+$|i", $str))
			{
				show_error('The URI you submitted has disallowed characters.', 400);
			}
		}

		// Convert programatic characters to entities
		$bad	= array('$',		'(',		')',		'%28',		'%29');
		$good	= array('&#36;',	'&#40;',	'&#41;',	'&#40;',	'&#41;');

		return str_replace($bad, $good, $str);
	}
526492
private function parseHeaders($str) {

		if(false === is_string($str)) {
			return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($str)), E_USER_ERROR);
		}
		
		$headers = [];
		$status  = [];

		foreach(explode("\n", $str) as $header) {
			
			if(preg_match('/(:)/is', $header)) {
				list($key, $value) = preg_split('/(:)/is', $header, 2);
			}
			else {
				$key = $header;
			}

			if(trim($key) !== '') {

				if(preg_match('/(https?\/[0-9]\.[0-9])/i', $key, $http)) {

					$status['code'] = null;

					if(preg_match('/([0-9]+)/', ltrim($key, $http[0]), $code)) {
						$status['code'] = $code[0];
					}

					$status['protocol'] = $http[0];
					$status['status'] 	= trim($key);
					$status['text'] 	= trim(ltrim(trim(ltrim($key, $status['protocol'])), $status['code']));
					
				}
				else {
					$headers[strtolower($key)] = trim($value);
				}
			}
		}

		return ['headers' => $headers, 'status' => $status];
	}