2

I need to parse data from a string the string looks like:

id|0;f|Luke;l|skywalker;email|[email protected];(etc...)

I would like to convert this to something like:

$t = array(
 'id' => 0,
 'f' => 'Luke',
 'l' => 'Skywalker',
 'email' => '[email protected]',
 //....
)

Now i know I can explode then for loop then explode again but is there a shortcut to this?

Like 1 line of 1 function in PHP that will do this?

Tkx

7
  • 4
    No, there is not a function in PHP called automatically_parse_my_string_kthx(). You're going to have to settle for something that isn't a single function call.
    – user142162
    Jun 11, 2013 at 1:58
  • Like is said in my question: "Now i know I can explode then for loop then explode again". I am looking for something less painful to execute or a quicker way
    – lasers
    Jun 11, 2013 at 1:58
  • @lasers: "something less painful" --- what could be less painful than 5 lines of trivial code? Oneliner that doesn't fit the screen width?
    – zerkms
    Jun 11, 2013 at 1:59
  • There's nothing built-in that does this. Call explode to split it on ;, loop over that, explode to split it on |, push them into the array.
    – Barmar
    Jun 11, 2013 at 2:00
  • @zerkms well its explode then for loop then explore again, its not that painful but 1 function call will be faster i guess
    – lasers
    Jun 11, 2013 at 2:00

1 Answer 1

9

This little snippet should take care of it in most cases:

parse_str(strtr($data, '|;', '=&'), $t);

It turns the string into something that looks like application/x-www-form-urlencoded and then parses it according to those rules.

Note that certain characters will get a different meaning such as %20 will be turned into spaces, etc.

4
  • 6
    /me goes to register a second account to be able to upvote this awesomeness twice
    – zerkms
    Jun 11, 2013 at 2:02
  • 2
    @zerkms No need to get a second account, I'll take care of it... yet then again... the more the merrier. Jun 11, 2013 at 2:08
  • +100... Truly awesome!!
    – anubhava
    Jun 11, 2013 at 2:12
  • @JoeFrambach Thanks :) string parsing can be great fun!
    – Ja͢ck
    Jun 11, 2013 at 3:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.