PHP - split a string of HTML attributes into an indexed array

html, php, split

Solution

Use SimpleXML:

<?php
$attribs = ' id= "header " class = "foo   bar" style ="background-color:#fff; color: red; "';

$x = new SimpleXMLElement("<element $attribs />");

print_r($x);

?>

This assumes that the attributes are always name/value pairs...

Problem

I've got a string with HTML attributes: ``` $attribs = ' id= "header " class = "foo bar" style ="background-color:#fff; color: red; "'; ``` How to transform that string into an indexed array, like: ``` array( 'id' => 'header', 'class' => array('foo', 'bar'), 'style' => array( 'background-color' => '#fff', 'color' => 'red' ) ) ``` so I can use the PHP array_merge_recursive function to merge 2 sets of HTML attributes. Thank you

Original source