0

I'm trying to get all strings wrapped in double quotes with this regexp:

"(?:[^"\\]|\\.)*"

I already tried it on this site: http://www.phpliveregex.com/ and it works, but when i put it in my php code like this:

if( preg_match('/"(?:[^"\\]|\\.)*"/', $input_line, $output_array) )
{
.
.
.
}

I'm getting this error:

Warning:  preg_match(): Compilation failed: missing terminating ] for character class at offset 15

what am i missing?

SOLVED:

AS mario pointed out, a backslash was being escaped by PHP I got it working like this:

if( preg_match('/"(?:[^"\\\]|\\.)*"/', $sLine, $matches) ){
.
.
.
}
Slacker616
  • 845
  • 1
  • 11
  • 20
  • 1
    The backslash escapes itself in PHP double or single quoted string context. `preg_match` will only see one backslash before the `]`. – mario Aug 04 '14 at 23:10
  • 1
    See also: [Right way to escape backslash \[ \ \] in PHP regex?](http://stackoverflow.com/q/11044136) – mario Aug 04 '14 at 23:12
  • thank you so much @mario I'd been trying to solve this for a couple of hours and I finally got it working. :D – Slacker616 Aug 04 '14 at 23:15

1 Answers1

3

The most reliable way to define regexes in PHP is like so:

$regex = <<<'REGEX'
/"(?:[^"\\]|\\.)*"/
REGEX;

Admittedly, it's not the most readable, but it ensures that the string is passed as-is to the regex engine and not interpreted by PHP in any way.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592