0

I have the follow string:

{item1:test},{item2:hi},{another:please work}

What I want to do is turn it into an array that looks like this:

[item1] => test
[item2] => hi
[another] => please work

Here is the code I am currently using for that (which works):

$vf = '{item1:test},{item2:hi},{another:please work}';
$vf = ltrim($vf, '{');
$vf = rtrim($vf, '}');
$vf = explode('},{', $vf);

foreach ($vf as $vk => $vv)
{
    $ve = explode(':', $vv);
    $vx[$ve[0]] = $ve[1];
}

My concern is; what if the value has a colon in it? For example, lets say that the value for item1 is you:break. That colon is going to make me lose break entirely. What is a better way of coding this in case the value has a colon in it?

4
  • 1
    Do you need to use this format? If not, I'd suggest JSON instead (which is easy to parse via json_decode()) Commented Mar 16, 2015 at 23:05
  • Convert to json: $vf = '{item1:test},{item2:hi},{another:please work}'; $vf = str_replace(['{',':','}'], ['{"','":"','"}'], $vf); var_dump($vf); var_dump(json_decode('['.$vf.']', true)); or $vf = '{item1:test},{item2:hi},{another:please work}'; $vf = str_replace(['},{','{',':','}'], ['","','{"','":"','"}'], $vf); var_dump($vf); var_dump(json_decode($vf, true)); Commented Mar 16, 2015 at 23:08
  • @MarkBaker So {colon:key:test} becomes {"colon":"key":"test"}? Commented Mar 16, 2015 at 23:09
  • It would if there were any examples like that in OP's string, but not in what they've posted Commented Mar 16, 2015 at 23:11

4 Answers 4

2

Why not to set a limit on explode function. Like this:

$ve = explode(':', $vv, 2);

This way the string will split only at the first occurrence of a colon.

Sign up to request clarification or add additional context in comments.

3 Comments

I wish I could accept 2 answers...cause this is just as good as the one I accepted.
its ok. glad I could help.
I like this answer better than than mine. Then you can simply: $vx[$ve[0]] = $ve[1];.
2

To address the possibility of the values having embedded colons, and for the sake of discussion (not necessarily performance):

$ve = explode(':', $vv);
$key = array_shift($ve);
$vx[$key] = implode(':', $ve);

...grabs the first element of the array, assuming the index will NOT have a colon in it. Then re-joins the rest of the array with colons.

1 Comment

This was my original thought but I couldn't find that function...thanks
1

Don't use effing explode for everything.

You can more reliably extract such simple formats with a trivial key:value regex. In particular since you have neat delimiters around them.

And it's far less code:

preg_match_all('/{(\w+):([^}]+)}/', $vf, $match);
$array = array_combine($match[1], $match[2]);

The \w+ just matches an alphanumeric string, and [^}]+ anything that until a closing }. And array_combine more easily turns it into a key=>value array.

Comments

0

Answering your second question:

If your format crashes with specific content it's bad. I think there are 2 types to work around.

  1. Escape delimiters: that would be, every colon and curly brackets have to be escaped which is strange, so data is delimited with e.g. " and only those quotation marks are escaped (than you have JSON in this case)
  2. Save data lengths: this is a bit how PHP serializes arrays. In that data structure you say, that the next n chars is one token.

The first type is easy to read and manipulate although one have to read the whole file to random access it. The second type would be great for better random accessing if the structure doesn't saves the amount of characters (since in UTF-8 you cannot just skip n chars by not reading them), but saving the amount of bytes to skip. PHP's serialize function produce n == strlen($token), thus I don't know what is the advantage over JSON.

Where possible I try to use JSON for communication between different systems.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.