tags:

views:

98

answers:

3

I have this regex:

preg_replace(
    '/\["'.$key.'"\] = (.+?);/is', '["'.$key.'"] = '.$newValue.';',
    $contents);

It writes an array value in a config file. I need to allow single or double quotes around the array key and I'm not sure how to do that. I didn't write this regex.

+2  A: 

You could replace the "find" regex to match both types of quotes:

'/\[[\'"]'.$key.'[\'"]\] = (.+?);/is'

This will even match:

["MegaKey'] = UberValue;

And if I were you, I'd put this configuration file on the list of things to rewrite without regexes.

Andomar
+1  A: 

Well, you can do back-referencing to match the correct set of quotes used (opened with double, closed with double)

preg_replace(
    '/\[([\"\']+)'.$key.'\\1\]\s=\s(.+?);/is', '[\\1'.$key.'\\1] = '.$newValue.';',
    $contents);

\\1 matches the first type of quote used

thephpdeveloper
+1 is it intentional to match any number of quotes like `["'"key"'"]`
Andomar
well, we can also match only one quote too using the `{1}`
thephpdeveloper
+4  A: 

The usual way to handle multiple quoting styles is to spell them out: /'a'|"a"/, duplicating what is inside the quotes, though it may very well be slightly different (such as to disallow an unescaped single quote within a single-quoted string.

'/\[("'.$key.'"|\''.$key.'\')\] = (.+?);/is'

You can also, sometimes, use a back reference:

'/\[([\'"])'.$key.'\\1\] = (.+?);/is'
Roger Pate
+1 nice options; I do think the back reference needs a double escape like `\\1`
Andomar
Thanks, been using raw string literals too much lately. :)
Roger Pate
+1 the backref is the best solution here, less likely to accept nonsense `['asdf"]`. \\1 would be necessary if the regex was in double quotes.
scribble