MatthiasMullie\Minify\JS::extractRegex PHP Method

extractRegex() protected method

The content inside the regex can contain characters that may be confused for JS code: e.g. it could contain whitespace it needs to match & we don't want to strip whitespace in there. The regex can be pretty simple: we don't have to care about comments, (which also use slashes) because stripComments() will have stripped those already. This method will replace all string content with simple REGEX# placeholder text, so we've rid all regular expressions from characters that may be misinterpreted. Original regex content will be saved in $this->extracted and after doing all other minifying, we can restore the original content via restoreRegex()
protected extractRegex ( )
    protected function extractRegex()
    {
        // PHP only supports $this inside anonymous functions since 5.4
        $minifier = $this;
        $callback = function ($match) use($minifier) {
            $count = count($minifier->extracted);
            $placeholder = '/' . $count . '/';
            $minifier->extracted[$placeholder] = $match[0];
            return $placeholder;
        };
        $pattern = '\\/.+?(?<!\\\\)(\\\\\\\\)*\\/[gimy]*(?![0-9a-zA-Z\\/])';
        // a regular expression can only be followed by a few operators or some
        // of the RegExp methods (a `\` followed by a variable or value is
        // likely part of a division, not a regex)
        $after = '[\\.,;\\)\\}]';
        $methods = '\\.(exec|test|match|search|replace|split)\\(';
        $this->registerPattern('/' . $pattern . '(?=\\s*(' . $after . '|' . $methods . '))/', $callback);
        // 1 more edge case: a regex can be followed by a lot more operators or
        // keywords if there's a newline (ASI) in between, where the operator
        // actually starts a new statement
        // (https://github.com/matthiasmullie/minify/issues/56)
        $operators = $this->getOperatorsForRegex($this->operatorsBefore, '/');
        $operators += $this->getOperatorsForRegex($this->keywordsReserved, '/');
        $this->registerPattern('/' . $pattern . '\\s*\\n(?=\\s*(' . implode('|', $operators) . '))/', $callback);
    }