preg_match(): Compilation Failed Due to Invalid Character Class Range
The error message "preg_match(): Compilation failed: invalid range in character class at offset 20" indicates that a regular expression pattern contains an invalid character class range. In this case, the issue has suddenly emerged after a PHP upgrade on the server, and we'll explore the reasons.
Reason for the Error:
PHP 7.3 upgraded the PCRE (Perl Compatible Regular Expressions) engine to PCRE2, which brought about several changes, including stricter validation of patterns. In particular, the hyphen (-) character is now treated differently in character classes.
Code Snippet:
The provided code uses a regular expression to validate usernames:
/^[a-z0-9]([0-9a-z_-\s])+$/i
In previous versions of PHP, the hyphen could be used anywhere within a character class if it was escaped or placed where it couldn't be interpreted as an indicator of a range.
Impact of PHP 7.3:
With PCRE2, the escape () is no longer ignored in hyphenated character classes. This means that in PHP 7.3 and later, the code above should be updated to:
/^[a-z0-9]([0-9a-z_-]\s)$/i
Solution:
To resolve the compilation error, ensure that hyphenated character classes follow these rules:
Additional Information:
The above is the detailed content of Why is my PHP preg_match() failing after upgrading to PHP 7.3 with a 'invalid range in character class' error?. For more information, please follow other related articles on the PHP Chinese website!