Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_match "Compilation failed: missing )"

its probably a stupid fault but I have a regex what should match on

  • allalaa
  • afkdsf[]
  • afadf43fds["guyish"]

but not on strings starting with a number

here is the code

preg_match('~^[A-Za-z][A-Za-z0-9]*(\[(?P<array>"(?:.*(?:(?<!\\)(?>\\\\)*\").*|.*)+(?:(?<!\\)(?>\\\\)*"))\]|\[\]|)$~',trim($item[0],"    \r"),$matches)

but when I execute it I get the error Compilation failed: missing ) at offset 95

while when I execute it here it works fine?

whats wrong with the code?

UPDATE

readable regex:

~
   ^
   [A-Za-z]
   [A-Za-z0-9]*
   (
      \[
      (?P<array>
      "
      (?:
          .*
          (?:
             (?<!\\)
             (?>\\\\)*
             \"
           )
           .*
        |
           .*
        )+
        (?:
           (?<!\\)
           (?>\\\\)*
           "
         )
       )
       \]
     |
     \[\]
     |
   )$
~x
like image 457
EaterOfCode Avatar asked Dec 08 '22 21:12

EaterOfCode


1 Answers

This regex is insane. I have a hard time believing you really need such a complicated one.

In any case the problem is that PHP is consuming the backslash for the PHP string. So you have to escape all the backslashes with another backslash.

And considering the number of backslashes you already have you'll probably go a little nuts doing it.

See also: Leaning toothpick syndrome

like image 144
Ariel Avatar answered Dec 28 '22 06:12

Ariel