1 ///
2 module phphelpers;
3 
4 import std..string;
5 import std.exception;
6 import std.conv;
7 
8 import std.variant;
9 
10 Variant phpUnserialize(ref string text) {
11 	Variant v;
12 	if(text.length == 0)
13 		return v;
14 
15 	auto colon = text.indexOf(":");
16 	enforce(colon != -1);
17 
18 	string type = text[0 .. colon];
19 	text = text[colon + 1 .. $];
20 
21 	switch(type) {
22 		default: assert(0);
23 		case "a":
24 			// PHP arrays are always AA. While it sometimes
25 			// uses int keys, I'm using strings here
26 			colon = text.indexOf(":");
27 			enforce(colon != -1);
28 			auto leng = to!int(text[0 .. colon]);
29 			text = text[colon + 1 .. $];
30 			enforce(text[0] == '{');
31 
32 			text = text[1 .. $];
33 
34 			Variant[string] aa;
35 			for(int a = 0; a < leng; a++) {
36 				// first is key, then is value
37 				auto key = phpUnserialize(text);
38 				auto value = phpUnserialize(text);
39 
40 				aa[key.coerce!string] = value;
41 			}
42 
43 			v = aa;
44 
45 			enforce(text[0] == '}', text[0 .. $]);
46 			text = text[1 .. $];
47 		break;
48 		case "i":
49 			auto semicolon = text.indexOf(";");
50 			enforce(semicolon != -1);
51 			auto number = to!int(text[0 .. semicolon]);
52 			text = text[semicolon + 1 .. $];
53 			v = number;
54 		break;
55 		case "s":
56 			colon = text.indexOf(":");
57 			enforce(colon != -1);
58 			auto leng = to!int(text[0 .. colon]);
59 			text = text[colon + 1 .. $];
60 			enforce(text[0] == '"');
61 
62 			string s = text[1 .. 1 + leng];
63 			text = text[1 + leng .. $];
64 			enforce(text[0..2] == `";`);
65 
66 			text = text[2 .. $];
67 
68 			v = s;
69 		break;
70 	}
71 
72 	return v;
73 }
74 
75 // convenience function so you don't have to pass a ref input
76 Variant unserialize(in string phptext) {
77 	string s = phptext;
78 	return phpUnserialize(s);
79 }
Suggestion Box / Bug Report