Search code examples
phpregexpreg-matchpreg-match-all

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


Solution

  • You can use a regex like

    '/(\w+)\s*=\s*"(.*?)"\s*(?=$|\w+\s*=)/ms'
    

    See the regex demo

    Pattern details:

    • The /s is a DOTALL modifier that makes the . match any symbol including a newline
    • The /m modifier makes $ match the end of the line
    • (\w+) - Group 1 capturing 1 or more alphanumeric or underscore characters
    • \s* - zero or more whitespaces
    • = - an equal sign
    • \s* - 0+ whitespaces
    • "(.*?)" - a double quote, zero or more any chars other than a newline as few as possible up to the first double quote and this quote as well (Group 2 is what is captured in between double quotes)
    • \s* - zero or more whitespaces
    • (?=$|\w+\s*=) -a positive lookahead requiring the end of string to appear right after the current position or one or more alphanumeric followed with zero or more whitespaces and an equal sign.