I have a string which is build up like this:
[propertyname]=[value]
Both the propertyname and the value can be encapsulated by either single or double quotes.
So i could receive a string which looks like this:
"height"='max'
or:
'height'='max'
As long as both the propertyname and value are encapsulated by the same type of quotes.
What i need to do is remove the quotes. But only around the propertyname and value! Because the following could very well be a valid string too:
"blaat"="Some 'random' blaat"
The end result should be:
blaat=Some 'random' blaat
I have the following regex which works. But it only works when i’m either checking for double quotes or single quotes. When i try to combine them with the | operator, then it doesn’t work anymore.
<?php
$string = '"height"=\'something "else" in here\'';
//echo preg_replace ( '#"(.*?)"#', '$1', $string );
//echo preg_replace ( '#\'(.*?)\'#', '$1', $string );
echo preg_replace ( '#("(.*?)"|\'(.*?)\')#', '$1', $string );
?>
So i could simply do two preg_replace calls, but that’s a nasty work around considering regex should be able to handle this in one call…
Any idea what the problem is?
Your regex should be matching correctly, but you have a problem: In your “combined regex”,
$1refers to the entire match (because the first set of parentheses encloses the entire match), so you’re replacing the match with itself, including the quotes.Now, you could simply drop the outer parentheses:
But then you have a different problem: You either need to replace the match with
$1or$2, depending on which half of the regex did match. Since you can’t know that in advance, that won’t be easy. You could possibly try and replace with$1$2, but I don’t know whether PHP would allow a backreference to a group that didn’t participate in the match.Better play it safe and use a regex that can handle both cases at once, including escaped quotes within the quoted strings: