Range out of order in character class

前端 未结 7 1582
广开言路
广开言路 2020-12-07 00:20

I\'m getting this odd error in the preg_match() function:

Warning: preg_match(): Compilation failed: range out of order in character class at offset 54

The l

相关标签:
7条回答
  • 2020-12-07 00:55

    This error is caused for an incorrect range. For example: 9-0 a-Z To correct this, you must change 9-0 to 0-9 and a-Z to a-zA-Z In your case you are not escaping the character "-", and then, preg_match try to parse the regex and fail with an incorrect range. Escape the "-" and it must solve your problem.

    0 讨论(0)
  • 2020-12-07 01:02

    While the other answers are correct, I'm surprised to see that no-one has suggested escaping the variable with preg_quote() before using it in a regex. So if you're looking to match an actual bracket or anything else that means something in regex, that'll be converted to a literal token:

    $escaped = preg_quote($gsmNumber);
    preg_match( '/<!--GSM\sPER\sNUMBER\s-\s'.$escaped.'\s-\sSTART-->(.*)<!--GSM\sPER\sNUMBER\s-\s'.$escaped.'\s-\sEND-->/s', $fileData, $matches);
    
    0 讨论(0)
  • 2020-12-07 01:03

    This is a bug in several versions of PHP, as I have just verified for the current 5.3.5 version, as packaged with XAMPP 1.7.4 on Windows XP home edition.

    Even some very simple examples exhibit the problem, e.g.,

        $pattern = '/^[\w_-. ]+$/';
        $uid = 'guest';
        if (preg_match($pattern, $uid)) echo 
          ("<style> p { text-decoration:line-through } </style>");
    

    The PHP folks have known about the bug since 1/10/2010. See http://pear.php.net/bugs/bug.php?id=18182. The bug is marked "closed" yet persists.

    0 讨论(0)
  • 2020-12-07 01:04

    You probably have people insert mobile numbers including +, -, ( and/or ) characters and just use these as is in your preg_match, so you might want to sanitize the data provided before using it (ie. by stripping these characters out completely).

    0 讨论(0)
  • 2020-12-07 01:05

    Hi I got the same error and solved it:

      Warning: preg_match(): Compilation failed: range out of order in character class at offset <N>
    

    Research Phase:

    .. Range out of order .. So there is a range defined which can't be used.

    .. at offset N .. I had a quick look at my regex pattern. Position N was the "-". It's used to define ranges like "a-z" or "0-9" etc.

    Solution

    I simply escaped the "-".

     \-    
    

    Now it is interpreted as the character "-" and not as range!

    0 讨论(0)
  • 2020-12-07 01:08

    I was receiving this error with the following sequence:

    [/-.]
    

    Simply moving the . to the beginning fixed the problem:

    [./-]
    
    0 讨论(0)
提交回复
热议问题