Home > Backend Development > PHP Tutorial > Why is my PHP preg_match() failing after upgrading to PHP 7.3 with a 'invalid range in character class' error?

Why is my PHP preg_match() failing after upgrading to PHP 7.3 with a 'invalid range in character class' error?

Barbara Streisand
Release: 2024-12-15 10:00:21
Original
495 people have browsed it

Why is my PHP preg_match() failing after upgrading to PHP 7.3 with a

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
Copy after login

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
Copy after login

Solution:

To resolve the compilation error, ensure that hyphenated character classes follow these rules:

  • Use the hyphen at the start or end positions only.
  • Escape the hyphen with a backslash () if it appears in any other position.

Additional Information:

  • The official PHP documentation for Unicode property escapes explains that previous versions of PCRE treated the hyphen as a literal character in any location of a character class.
  • With PCRE2, a specific error is now thrown for invalid character class ranges, making the issue clearer.
  • For PHP versions prior to 7.3, the workaround is to escape the hyphen, but this is no longer necessary in PHP 7.3 and later.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template