Mortaza Faryabi Mortaza Faryabi - 5 months ago 11
PHP Question

extract string in double quotation(there are pair double quotations at string)

i have a string

$sting=
' [
type="user"
name="ali"
key="#$WRE"

//problem
address="{
"type":"hellow"
}"
]';


and i extract data with key=value format

for (;;) {
if(!preg_match('~([A-Za-z0-9]+)\=\"([^\"]*)\"~m', $string,$match)){
break;
}
$string=str_replace($match[0], '', $string);

$dataArray[$match[1]]=$match[2];
}

echo "<br><pre>";
print_r($dataArray);
echo "<br></pre>";


but output is



<br><pre>Array
(
[type] = user
[name] = ali
[key] = #$WRE
[address] = {

)
<br></pre>




According to [address]
(im not good at english For this reason, there may be errors in the sentences)

please help me

Answer

You can use a regex based on an alternation group inside a branch reset construct ((?|...|...)) where capturing groups IDs are the same.

'/(\w+)=(?|"({.*?})"|"(.*?)")/s'

See the regex demo

Pattern details:

  • The /s is a DOTALL modifier that makes the . match any symbol including a newline
  • (\w+) - Group 1 capturing 1 or more alphanumeric or underscore characters
  • = - an equal sign
  • (?|"({.*?})"|"(.*?)") - a branch reset alternation group matching either:
    • " - a double quote,
    • ({.*?}) - Group 2 capturing a {, any 0+ characters, }
    • " - a double quote
      OR
    • " - a double quote
    • (.*?) - Group 2 capturing any 0+ characters as few as possible up to the first
    • " - double quote.
Comments