Andy
Andy

Reputation: 1043

PHP: from string to array: argument => parametr

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"
)

Upvotes: 1

Views: 201

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173572

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();
}

Edit

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;

Upvotes: 3

Related Questions