Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exploding string using multiple criterias in PHP [closed]

Tags:

php

explode

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

like image 609
lasers Avatar asked Dec 04 '25 07:12

lasers


1 Answers

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.

like image 76
Ja͢ck Avatar answered Dec 06 '25 20:12

Ja͢ck