Will Fris's WordPress Weblog











{20090818}   Using php’s explode() in a recursive manner

While working in PHP today, I wanted to have a way to turn a string like:
name=value,name=,name=value
(maybe even: name=value,name,name=value,=value,name=value )
I tried:
explode('=' , explode(',' , $array));
But unfortunately that did not work, since explode() does not except an array as argument. (And the small fact that I got the parameters mixed up first time around did not help either. 🙂 )

I could not immediately come up with a way to do this, so I searched for something like: `php recursive explode`.
Among others, I found `PHP split or explode`.
One of the questions that poster asks is: “Is it recommended to avoid to use the split() function and other PHP functions ?”
To answer this, I went to the php split-function page in the manual, which I can do by typing: `p split` in the location bar since I use firefox and made `p` the keyword for this search engine.
(I actually type: `:o p split`, since I am using the vimperator add-on for firefox, maybe more about that some other time though.)

Nonetheless, that page did not answer my question either.
I however digressed as I do very often, going off to write this blog-entry and to answer my new question:
What is the difference between str_split and explode ?
Well , in short to this is:

str_split
splits a string by a certain amount of chars and returns an array

while

explode
splits a string by a certain other string and returns an array

.
This however did not solve the problem , so I searched a bit more: `explode to associative array` .
Which gave me some useful hits that were good for hints, but did not provide a way to do key-value_pairs.

I thought it took too long to find a solution, so I wrote my own, in the neglect of it being an `unelegant` solution.
So for now, this is my solution to the problem:


<?php
#I have absolutely no idea why explode() should have it's delimiter as first parameter(as it says in the manual).
function splita ($string , $delimiters = ' ')
	{
		$array                                      =  array();
		is_array($delimiters) ? NULL : $delimiters  =  array_slice(func_get_args() , 1);//Check if array is empty?
		if (count($delimiters) !== 2){throw new Exception('Sorry, not yet supported.');}
		reset($delimiters);
		$arr                                        =  explode(current($delimiters) , $string);
		next($delimiters);
		foreach ($arr as $index => $name_value_pair)
			{
				$tmp  =  explode(current($delimiters) , $name_value_pair);
				if ($tmp === FALSE)
					{//echo 'geen value:' . implode(':',$tmp);
						$array[$tmp[0]]  =  '';
					}
				elseif (isset($tmp[1]))
					{//echo 'name-value:' . implode(':',$tmp);
						$array[$tmp[0]]  =  $tmp[1];
					}
				else
					{//echo 'just-value:' . implode(':',$tmp);
						$array[]         =  $tmp[0];
					}
			}
		return $array;
	}
?>

I will probably change it again sometime, there’s also stuff I did not take into account yet.
Anyway, for now, it will do.

Update (Sun 2009-08-23, 15:55.47 CEST):
I knew it…
The parse_str() function… doh!

Advertisements


fred says:

you just have to implode() the result from each explode() then explode() the string again. Not sure about performance on this though.



fred says:

sorry…made a mistake there. It should be:
function explodeRecursive (array of strings, array of delimiter)
take the 1st delimiter from array
explode each string and merge the arrays from explode into 1 array
call explodeRecursive (the merged array, delimiter array after unset() the first element)



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

et cetera
%d bloggers like this: