Reputation: 1043
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
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