Home > Backend Development > PHP Tutorial > Why Does `preg_match()` Fail with 'Invalid Range in Character Class' After a PHP Upgrade?

Why Does `preg_match()` Fail with 'Invalid Range in Character Class' After a PHP Upgrade?

DDD
Release: 2024-12-09 01:11:10
Original
619 people have browsed it

Why Does `preg_match()` Fail with

preg_match(): Invalid Range in Character Class After PHP Upgrade

The error "preg_match(): Compilation failed: invalid range in character class at offset" typically occurs when a hyphen (-) is used incorrectly within a character class in a regular expression.

In the provided code snippet:

else if(!preg_match("/^[a-z0-9]([0-9a-z_-\s])+$/i", $subuser)){
Copy after login

There is a hyphen "-" within the character class [0-9a-z_-s]. In older versions of PHP, escaping the hyphen with a backslash , or placing it at the beginning or end of the character class, allowed its use.

PHP 7.3 and PCRE2 Changes

However, with PHP 7.3 and the migration to the PCRE2 library, the use of the hyphen is more restricted. In PCRE2, hyphens can only be used at the beginning or end of a character class.

To resolve this issue, modify the character class as follows:

else if(!preg_match("/^[a-z0-9]([0-9a-z_0-9_-])+$/i", $subuser)){
Copy after login

This places the hyphen at the beginning of the character class, allowing it to be used correctly.

Additional Notes

  • Escaping the hyphen with , as suggested in the provided answer, is no longer necessary in PHP 7.3 and above.
  • The PCRE2 library may introduce other changes in regular expression syntax. It's important to review the documentation and make necessary adjustments to your code when upgrading to PHP 7.3 or later.

The above is the detailed content of Why Does `preg_match()` Fail with 'Invalid Range in Character Class' After a PHP Upgrade?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template