Slacker616
Slacker616

Reputation: 855

Regular expression for strings in double quotes not working?

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) ){
.
.
.
}

Upvotes: 0

Views: 281

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324810

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.

Upvotes: 3

Related Questions