Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

php

split

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

like image 332
abernier Avatar asked Jul 05 '09 10:07

abernier


People also ask

How to split string in array PHP?

The str_split() function splits a string into an array.

How to divide a string into various elements in PHP?

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.

What is the use of explode function in PHP?

The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string. Note: This function is binary-safe.


3 Answers

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...

like image 58
Ken Keenan Avatar answered Nov 06 '22 15:11

Ken Keenan


Easy way could be also:

$atts_array = current((array) new SimpleXMLElement("<element $attribs />"));
like image 41
Mariyo Avatar answered Nov 06 '22 16:11

Mariyo


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

like image 8
Gumbo Avatar answered Nov 06 '22 15:11

Gumbo