Invalid Range in Character Class After PHP Upgrade
This error, "preg_match(): Compilation failed: invalid range in character class at offset 20," typically occurs when a PHP upgrade introduces changes to the PCRE engine or the Unicode engine used in your code.
PHP PCRE2 Migration
PHP 7.3 and later versions utilize PCRE2, which introduced several backward-incompatible changes. One such change is the stricter validation of character class patterns.
Hyphens in Character Classes
Previously, you could escape a hyphen (-) and use it anywhere within a character class. However, in PHP 7.3 onwards, you must place the hyphen either at the start or end of the character class only.
Solution
To resolve this error, ensure that hyphens (-) are placed correctly within character classes. If you need to use a hyphen as a character within the class, you must escape it (e.g., -).
Example
// Invalid (in PHP 7.3+) preg_match("/^[a-z0-9]([0-9a-z_\-\s])+$/i", $subuser); // Valid (in PHP 7.3+) preg_match("/^[a-z0-9]([0-9a-z\-_\s])+$/i", $subuser);
Additional Considerations
The above is the detailed content of Why Am I Getting 'preg_match(): Compilation failed: invalid range in character class' After My PHP Upgrade?. For more information, please follow other related articles on the PHP Chinese website!