tags:

views:

86

answers:

5
+1  Q: 

PHP string split

Hi,

I have this $str value :

[{\"firstname\":\"guest1\",\"lastname\":\"one\",\"age\":\"22\",\"gender\":\"Male\"},{\"firstname\":\"guest2\",\"lastname\":\"two\",\"age\":\"22\",\"gender\":\"Female\"}]

I want to split it into the following:

firstname:guest1,lastname:one,age:22
firstname:guest2,lastname:two,age:22

I tried explode (",",$str) , but it explode all using , as delimiter and I don't get what I want

anyone can help me ?

A: 

If you split on ,'s then you will get all the other crap that surrounds it. You would then have to strip that off.

Looks a lot like JSON data to me, where is this string coming from?

Josh K
it comes from a usual form posted in website...
redcoder
the datatype is string when i use var_dump
redcoder
JSON data is a string. See http://json.org/
Marc B
+4  A: 

As Josh K points out, that looks suspiciously like a JSON string. Maybe you should do a json_decode() on it to get the actual data you're looking for, all organized nicely into an array of objects.

EDIT: it seems your string is itself wrapped in double quotes ", so you'll have to trim those away before you'll be able to decode it as valid JSON:

$str_json = trim($str, '"');
$guests = json_decode($str_json);
var_dump($guests);

I get this output with the var_dump(), so it's definitely valid JSON here:

array(2) {
  [0]=>
  object(stdClass)#1 (4) {
    ["firstname"]=>
    string(6) "guest1"
    ["lastname"]=>
    string(3) "one"
    ["age"]=>
    string(2) "22"
    ["gender"]=>
    string(4) "Male"
  }
  [1]=>
  object(stdClass)#2 (4) {
    ["firstname"]=>
    string(6) "guest2"
    ["lastname"]=>
    string(3) "two"
    ["age"]=>
    string(2) "22"
    ["gender"]=>
    string(6) "Female"
  }
}

JSON (JavaScript Object Notation) is not CSV (comma-separated values). They're two vastly different data formats, so you can't parse one like the other.

To get your two strings, use a loop to get the keys and values of each object, and then build the strings with those values:

foreach ($guests as $guest) {
    $s = array();

    foreach ($guest as $k => $v) {
        if ($k == 'gender') break;
        $s[] = "$k:$v";
    }

    echo implode(',', $s) . "\n";
}

Output:

firstname:guest1,lastname:one,age:22
firstname:guest2,lastname:two,age:22

(Assuming you do want to exclude the genders for whatever reason; if not, delete the if ($k == 'gender') break; line.)

BoltClock
i get a NULL value.. using the $guests = json_decode(stripslashes($str));var_dump($guests);
redcoder
@redcoder: strange. I copied the string from your question and could parse it correctly; could you `var_dump($str);` so I can see what the actual `$str` is?
BoltClock
No need for a `stripslashes`. See: http://pastebin.com/tGpQewqi
nikc
...if it still won't work, try `var_dump(function_exists('json_decode'));`. (Should output `bool(true)`).
nikc
@nikc: I removed the `stripslashes()` call. Also, if the function didn't exist, PHP would throw a fatal error instead of it returning NULL.
BoltClock
Ah, that's true.
nikc
var_dump give these result:string(171) ""[{\"firstname\":\"guest1\",\"lastname\":\"two\",\"age\":\"22\",\"gender\":\"Male\"},{\"firstname\":\"guest2\",\"lastname\":\"one\",\"age\":\"33\",\"gender\":\"Female\"}]""
redcoder
@redcoder: I see it now: the JSON string is enclosed in double quotes. I'll update my answer so it trims off those extra quotes and allows the string to be read as valid JSON.
BoltClock
in fact var_dump(function_exists('json_decode')); return bool(true). so it is a JSON
redcoder
@BoltClock : strange enough ... that edited codes still produce NULL
redcoder
just to make my problem clearer, here is the code I wrote: $str_json = trim($userdetails->other_guests, '"'); $guests = json_decode($str_json); echo "<pre align='left'>"; var_dump($guests); var_dump($userdetails->other_guests); echo "</pre>";
redcoder
And here is the results:NULLstring(171) ""[{\"firstname\":\"guest1\",\"lastname\":\"two\",\"age\":\"22\",\"gender\":\"Male\"},{\"firstname\":\"guess2\",\"lastname\":\"one\",\"age\":\"33\",\"gender\":\"Female\"}]""
redcoder
@redcoder: try it with `stripslashes()` and see if that works.
BoltClock
A: 

If that is valid json, just run it through json_decode() to get a native php array...

Note that you may need to run it through stripslashes() first, as it appears you may have magic_quotes_gpc set... You can conditionally call it by checking with the function get_magic_quotes_gpc:

if (get_magic_quotes_gpc()) {
    $_POST['foo'] = stripslashes($_POST['foo']);
}
$array = json_decode($_POST['foo']);
ircmaxell
i doubt it is a JSON because the original datatype is string when I use var_dump...
redcoder
JSON is an encoding. It encodes information into a string. So the original datatype should be string if it's JSON...
ircmaxell
@redcoder: JSON is not an object data type itself. It's a string formatted so that when programs process it, an object is obtained.
BoltClock
A: 

You need to use preg_replace function.

    $ptn = "/,\\"gender\\":\\"\w+\\"\}\]?|\\"|\[?\{/";
    $str = "[{\"firstname\":\"guest1\",\"lastname\":\"one\",\"age\":\"22\",\"gender\":\"Male\"},{\"firstname\":\"guest2\",\"lastname\":\"two\",\"age\":\"22\",\"gender\":\"Female\"}]";
    $rpltxt = "";
    echo preg_replace($ptn, $rpltxt, $str);

You can the php regular expression tester to test the result.

or use preg_match_all

$ptn = "/(firstname)\\":\\"(\w+)\\",\\"(lastname)\\":\\"(\w+)\\",\\"(age)\\":\\"(\d+)/";
$str = "[{\"firstname\":\"guest1\",\"lastname\":\"one\",\"age\":\"22\",\"gender\":\"Male\"},{\"firstname\":\"guest2\",\"lastname\":\"two\",\"age\":\"22\",\"gender\":\"Female\"}]";
preg_match_all($ptn, $str, $matches);
print_r($matches);
unigg
A: 

i still haven't get a chance to retrieve the JSON : I var_dump the trimmed value as :

    $str_json = trim($userdetails->other_guests, '"');

    $guests = json_decode($str_json);

    var_dump($str_json,$guests);

WHERE $userdetails->other_guests is the $str value I had before...

I get the following output :

string(169) "[{\"firstname\":\"guest1\",\"lastname\":\"one\",\"age\":\"22\",\"gender\":\"Male\"},{\"firstname\":\"guest2\",\"lastname\":\"two\",\"age\":\"23\",\"gender\":\"Female\"}]" NULL

This mean the decoded json are NULL... strange

redcoder
ooh.. actually i have to decode_jason twice to get the object
redcoder