Moskau Peterson
Moskau Peterson

Reputation: 95

Preg_replace range character class

It is saying this and I wonder why that happened. It didn't happen before.

Warning: preg_replace(): Compilation failed: invalid range in character class at offset 16 in messenger.php on line 158

$pattern = array(
             "/[^@\s]*@[^@\s]*\.[^@\s]*/",
            "/[a-zA-Z]*[:\/\/]*[A-Za-z0-9\-_]+\.+[A-Za-z0-9\.\/%&=\?\-_]+/i",
            '/\+?[0-9][0-9()-\s+]{4,20}[0-9]/'
        );
        $replacement    = array(
            "[removed email]",
            "[removed url]",
            "[removed phone]"
        );
        $message_text   = preg_replace($pattern, $replacement, $message_text);

Line 158 is the last one with $message_text.

Who can help?

Upvotes: 0

Views: 586

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

In \+?[0-9][0-9()-\s+]{4,20}[0-9], you misplaced the hyphen and the regex engine thinks you are trying to build a range between ) and \s.

It is not possible for a shorthand class to appear at the range boundary.

Here is an error appearing in Debuggex.com:

enter image description here

And here is an excerpt from the PCRE Reference:

An error is generated if a POSIX character class (see below) or an escape sequence other than one that defines a single character appears at a point where a range ending character is expected. For example, [z-\xff] is valid, but [A-\d] and [A-[:digit:]] are not.

Use \+?[0-9][0-9()\s+-]{4,20}[0-9], or escape the hyphen like \+?[0-9][0-9()\-\s+]{4,20}[0-9].

See working regex demo

Upvotes: 1

Toto
Toto

Reputation: 91415

You've forgotten to escape the dash in:

'/\+?[0-9][0-9()-\s+]{4,20}[0-9]/'
//       here __^

should be:

'/\+?[0-9][0-9()\-\s+]{4,20}[0-9]/'

Upvotes: 0

Related Questions