PHP Tip: styles2array

Today I needed to write a bit of code to take the style attribute off of an HTML tag and convert it into something I could use inside PHP.

My first thought was to use regular expressions, but it occurred to me that there might be a simpler way to do it with just a couple of explodes.

Just in case this might help someone else out there, I thought I’d post it.

So, assuming you will pass something like “width:1090px;left:-340px;top:-144px;” to the function
you should get back the following:


Array
(
    [width] => 1090px
    [left] => -340px
    [top] => -144px
)


function styles2array($styles){
	$styles = rtrim($styles, "; ");
	$arr = explode(";", $styles);
	$return = array();
	for($i=0; $i<sizeof($arr); $i++)
		{
		$split = explode(":", $arr[$i]);
		$return[$split[0]] = $split[1];
		}
	return $return;
	}

Cheers!

-Matt

Work with us on your next project! Click here to get started.

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment