1

I have got strings like:

name="n e" content="12" icon="favicon.ico"

What is the best and quickest way to parse it as such array:

Array
(
    [name] => "n e"
    [content] => "12"
    [icon] => "favicon.ico"
)

1 Answer 1

3

This should do it, using preg_match_all() to get all the groups and array_combine() to form the final array:

if (preg_match_all('/(\w+)="([^"]*)"/', $str, $matches)) {
    return array_combine($matches[1], $matches[2]);
} else {
    return array();
}

This alternative breaks when there are spaces in between the double quotes; otherwise it works as well:

parse_str(str_replace(array(' ', '"'), array('&', ''), $s), $a);
return $a;
Sign up to request clarification or add additional context in comments.

1 Comment

@JonStirling Upon first sight it seemed to work, but as OP pointed out, it breaks when spaces are inside the double quoted strings :/ the preg method works of course :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.