Remove extraneous space in a given XPath expression

@param  string $expr Original XPath expression
@return string       Minified XPath expression
965858
public static function minify($expr)
	{
		$old     = $expr;
		$strings = [];

		// Trim the surrounding whitespace then temporarily remove literal strings
		$expr = preg_replace_callback(
			'/"[^"]*"|\'[^\']*\'/',
			function ($m) use (&$strings)
			{
				$uniqid = '(' . sha1(uniqid()) . ')';
				$strings[$uniqid] = $m[0];

				return $uniqid;
			},
			trim($expr)
		);

		if (preg_match('/[\'"]/', $expr))
		{
			throw new RuntimeException("Cannot parse XPath expression '" . $old . "'");
		}

		// Normalize whitespace to a single space
		$expr = preg_replace('/\\s+/', ' ', $expr);

		// Remove the space between a non-word character and a word character
		$expr = preg_replace('/([-a-z_0-9]) ([^-a-z_0-9])/i', '$1$2', $expr);
		$expr = preg_replace('/([^-a-z_0-9]) ([-a-z_0-9])/i', '$1$2', $expr);

		// Remove the space between two non-word characters as long as they're not two -
		$expr = preg_replace('/(?!- -)([^-a-z_0-9]) ([^-a-z_0-9])/i', '$1$2', $expr);

		// Remove the space between a - and a word character, as long as there's a space before -
		$expr = preg_replace('/ - ([a-z_0-9])/i', ' -$1', $expr);

		// Remove the spaces between a number and the div operator and the next token
		$expr = preg_replace('/((?:^|[ \\(])\\d+) div ?/', '$1div', $expr);

		// Remove the space between the div operator the next token
		$expr = preg_replace('/([^-a-z_0-9]div) (?=[$0-9@])/', '$1', $expr);

		// Restore the literals
		$expr = strtr($expr, $strings);

		return $expr;
	}
692669
public static function spaceless(string $s)
	{
		$s = trim($s);
		$s = self::replace($s, '#\s#', '');

		return $s;
	}
890123
public function whereNotNull($expr)
    {
        foreach ($this->queries as $query) {
            $query->whereNotNull($expr);
        }

        return $this;
    }
878844
protected function compileExpression($expr)
    {
        $expr = trim($expr);

        if (strncasecmp($expr, 'SELECT ', 7) === 0) {
            // It is as a raw subquery. Skip this, because the Builder of the subquery has should quoted this already.
            return  $expr;
        }

        $n = strlen($expr);
        $i = 0;
        while ($i < $n) {
            $ch = $expr[$i];
            if (stripos('abcdefghijklmnopqrstuvwxyz_', $ch) !== false) {
                // Is it a table/field/alias or a function?
                $k = $i; // first index of this part
                while (++$i < $n && stripos('abcdefghijklmnopqrstuvwxyz0123456789$_', $expr[$i]) !== false);
                $name = substr($expr, $k, $i - $k);
                $j = $i; // first index of the next part
                if (in_array(strtoupper($name), static::$keywords)) {
                    $expr = substr($expr, 0, $k) . strtoupper($name) . substr($expr, $j);
                }
                else {
                    while ($i < $n && $expr[$i] == ' ') ++$i; // skip spaces
                    if ($i < $n && $expr[$i] == '(') {
                        // It's a function! Take the arguments an translate the function if needed...
                        $args = [];
                        $braces = 1;
                        $j = $i + 1; // first index of the argument
                        while (++$i < $n && $braces > 0) {
                            $ch = $expr[$i];
                            if ($ch == ')') {
                                $braces--;
                            }
                            else if ($ch == '(') {
                                $braces++;
                            }
                            else if ($braces == 1 && $ch == ',') {
                                $args[] = substr($expr, $j, $i - $j);
                                $j = $i + 1;
                            }
                            else if ($ch == '"' || $ch == "'" || $ch == '`' || $ch == '[') { // masked literal
                                $c = $ch == '[' ? ']' : $ch;
                                while (++$i < $n && $expr[$i] != $c);
                            }
                            else if ($ch == '-' && $i + 2 < $n && $expr[$i + 1] == '-' && $expr[$i + 2] == ' ') { // comment
                                $i += 2;
                                while (++$i < $n && $expr[$i] != PHP_EOL);
                            }
                        }
                        if ($i - $j - 1 > 0) {
                            $args[] = substr($expr, $j, $i - $j - 1);
                        }

                        $args = array_map([$this, 'compileExpression'], $args);
//                        $args = array_map(function ($arg) {
//                            return $this->compileExpression($arg);
//                        }, $args);
                        $repl = $this->compileFunction($name, $args);
                        $j = $i; // first index of the next part
                    }
                    else {
                        // It's a table, field, or alias! Quote this one!
                        $repl = $this->db->quoteName($name);
                    }
                    // Replace the original term with the quoted part.
                    $expr = substr($expr, 0, $k) . $repl . substr($expr, $j);
                    $j = strlen($repl) - $j + $k; // difference of characters after replacing
                    $i += $j;
                    $n += $j;
                }
            }
            else if ($ch == '(') {
                // Is it a embedded subquery?
                while (++$i < $n && $expr[$i] == ' '); // skip spaces
                if (strcasecmp(substr($expr, $i, 7), 'SELECT ') === 0) {
                    // Yes, it is a embedded subquery! Skip this, because the Builder of the subquery has should quoted this already.
                    $i += 6;
                    $braces = 1;
                    while (++$i < $n && $braces > 0) {
                        $ch = $expr[$i];
                        if ($ch == ')') {
                            $braces--;
                        }
                        else if ($ch == '(') {
                            $braces++;
                        }
                        else if ($ch == '"' || $ch == "'" || $ch == '`' || $ch == '[') { // masked literal
                            $c = $ch == '[' ? ']' : $ch;
                            while (++$i < $n && $expr[$i] != $c);
                        }
                        else if ($ch == '-' && $i + 2 < $n && $expr[$i + 1] == '-' && $expr[$i + 2] == ' ') { // comment
                            $i += 2;
                            while (++$i < $n && $expr[$i] != PHP_EOL);
                        }
                    }
                }
            }
            else if ($ch == ':') { // named placeholder
                while (++$i < $n && stripos('abcdefghijklmnopqrstuvwxyz0123456789$_', $expr[$i]) !== false);
                ++$i;
            }
            else if ($ch == '"' || $ch == "'" || $ch == '`' || $ch == '[') { // masked literal
                $c = $ch == '[' ? ']' : $ch;
                while (++$i < $n && $expr[$i] != $c);
                ++$i;
            }
            else if ($ch == '-' && $i + 2 < $n && $expr[$i + 1] == '-' && $expr[$i + 2] == ' ') { // comment
                $j = $i + 2;
                while (++$j < $n && $expr[$j] != PHP_EOL);
                ++$j;
                // Remove the comment
                $expr = substr($expr, 0, $i) . substr($expr, $j);
                $n -= $j - $i; // difference of characters after replacing
            }
            else {
                ++$i;
            }
        }

        return $expr;
    }
520193
protected function getMatch($expr)
	{
		if (preg_match($this->regexp, $expr, $m))
		{
			foreach ($m as $name => $match)
			{
				if ($match !== '' && isset($this->callbacks[$name]))
				{
					return [$name, $this->getArguments($m, $name)];
				}
			}
		}

		return null;
	}
1088641
public static function extractPluralCount($expr)
    {
        $parts = explode(';', $expr, 2);
        $nplurals = explode('=', trim($parts[0]), 2);
        if (strtolower(rtrim($nplurals[0])) != 'nplurals') {
            return 1;
        }
        if (count($nplurals) == 1) {
            return 1;
        }

        return intval($nplurals[1]);
    }
1234898
protected function getParamKeyByExpr(ExprInterface $expr)
    {
        return str_replace('.', '', $expr->getField()) . ucfirst($expr->getExpression()) . uniqid();
    }
185779
protected function _parseVariable($expr)
    {
        $tok = explode('|', $expr);
        $res = $this->_parseFinal(array_shift($tok), $this->_allowedInVar, $this->_excludedInVar);

        foreach ($tok as $modifier) {
            if (!preg_match('/^(\w+)(?:\:(.*))?$/', $modifier, $m)) {
                $this->doError2('errors.tpl.tag.modifier.invalid', $this->_currentTag, $modifier);
            }

            if (isset($m[2])) {
                $targs = $this->_parseFinal($m[2], $this->_allowedInVar, $this->_excludedInVar, true, ',', ':');
                array_unshift($targs, $res);
            } else {
                $targs = array($res);
            }

            if ($path = $this->_getPlugin('cmodifier', $m[1])) {
                require_once $path[0];
                $fct = $path[1];
                $res = $fct($this, $targs);
            } elseif ($path = $this->_getPlugin('modifier2', $m[1])) {
                $res = $path[1].'($t, '.implode(',', $targs).')';
                $this->_pluginPath[$path[0]] = true;
            } elseif ($path = $this->_getPlugin('modifier', $m[1])) {
                $res = $path[1].'('.implode(',', $targs).')';
                $this->_pluginPath[$path[0]] = true;
            } else {
                if (isset($this->_modifier[$m[1]])) {
                    $res = $this->_modifier[$m[1]].'('.$res.')';
                } else {
                    $this->doError2('errors.tpl.tag.modifier.unknown', $this->_currentTag, $m[1]);
                }
            }
        }

        return $res;
    }
842117
protected ElemTemplateElement getElemFromExpression(Expression expr)
  {
  	ExpressionNode parent = expr.exprGetParent();
  	while(null != parent)
  	{
  		if(parent instanceof ElemTemplateElement)
  			return (ElemTemplateElement)parent;
  		parent = parent.exprGetParent();
  	}
  	throw new RuntimeException(XSLMessages.createMessage(XSLTErrorResources.ER_ASSERT_NO_TEMPLATE_PARENT, null));
  	// "Programmer's error! expr has no ElemTemplateElement parent!");
  }
50150
private static function removePrefix($str, $prefix)
    {
        if (substr($str, 0, strlen($prefix)) == $prefix) {
            return substr($str, strlen($prefix));
        }
        return null;
    }
149499
protected function evaluate($expr, DOMNode $node = null)
	{
		return (isset($node)) ? $this->xpath->evaluate($expr, $node) : $this->xpath->evaluate($expr);
	}
1210448
function select( $expr ) {

        $clone = clone $this;

        if ( $clone->select === null ) {

            $clone->select = func_get_args();

        } else {

            $clone->select = array_merge( $clone->select, func_get_args() );

        }

        return $clone;

    }
215343
protected function getFullClassToExtend($extend)
    {
        if (empty($extend)) {
            return '';
        }
        $appNamespace = Helpers::getAppNamespace();

        if (starts_with($extend, $appNamespace)) {
            $extend = str_replace($appNamespace, '', $extend);
        }

        return $appNamespace . trim($extend, '\\');
    }
895285
private function prepareRegexp($exp)
    {
        // remove surrounding '/' marks so that they don't get escaped in next step
        if ($exp{0} !== '/' || $exp{strlen($exp) - 1} !== '/') {
            $exp = '/' . $exp . '/';
        }

        // if they did not escape / chars; we do that for them
        $exp = preg_replace('/([^\\\])\/([^$])/', '$1\/$2', $exp);

        return $exp;
    }
667671
public function getType($expr)
	{
		$match = $this->getMatch($expr);

		return (isset($match, $this->matchGroup[$match[0]])) ? $this->matchGroup[$match[0]] : null;
	}
1300922
public function leaveExpression(Expression $expr)
    {
        if ($expr instanceof OrX || $expr instanceof AndX) {
            $hash = spl_object_hash($expr);

            if ($expr instanceof OrX) {
                $composite = $this->qb->expr()->orX();
                $composite->addMultiple($this->map[$hash]);
            } else {
                $composite = $this->qb->expr()->andX();
                $composite->addMultiple($this->map[$hash]);
            }

            unset($this->hashes[array_search($hash, $this->hashes)]);

            if (!count($this->hashes)) {
                $this->qb->andWhere($composite);
            } else {
                $lastHash = end($this->hashes);

                $this->map[$lastHash][] = $composite;
            }
        }

        return $expr;
    }
1162339
protected function evaluateExpression($expr)
	{
		$original = $expr;
		foreach ($this->getOptimizationPasses() as $regexp => $methodName)
		{
			$regexp = str_replace(' ', '\\s*', $regexp);
			$expr   = preg_replace_callback($regexp, [$this, $methodName], $expr);
		}

		return ($expr === $original) ? $expr : $this->evaluateExpression(trim($expr));
	}