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
The str_split() function splits a string into an array.
explode() is a built in function in PHP used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.
The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string. Note: This function is binary-safe.
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...
Easy way could be also:
$atts_array = current((array) new SimpleXMLElement("<element $attribs />"));
                        You could use a regular expression to extract that information:
$attribs = ' id= "header " class = "foo   bar" style ="background-color:#fff; color: red; "';
$pattern = '/(\\w+)\s*=\\s*("[^"]*"|\'[^\']*\'|[^"\'\\s>]*)/';
preg_match_all($pattern, $attribs, $matches, PREG_SET_ORDER);
$attrs = array();
foreach ($matches as $match) {
    if (($match[2][0] == '"' || $match[2][0] == "'") && $match[2][0] == $match[2][strlen($match[2])-1]) {
        $match[2] = substr($match[2], 1, -1);
    }
    $name = strtolower($match[1]);
    $value = html_entity_decode($match[2]);
    switch ($name) {
    case 'class':
        $attrs[$name] = preg_split('/\s+/', trim($value));
        break;
    case 'style':
        // parse CSS property declarations
        break;
    default:
        $attrs[$name] = $value;
    }
}
var_dump($attrs);
Now you just need to parse the classes of class (split at whitespaces) and property declarations of style (a little bit harder as it can contain comments and URLs with ; in it).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With