How to find out if a string is a serialized object/array or just a string?
Is there some reliable way to find out whether a string variable is just a string or a strin开发者_如何学Pythong representation of a serialized object/array?
You can call unserialize(string $str)
function: it returns false
, if string cannot be unserialized.
Well, you can tell by looking at the format. When you serialize an array, you get a string that looks like a:1:{i:0;s:3:"foo"}
And if you serialize an object, you get: o:7:"myclass":1:{s:3:"foo";s:3:"bar";}
.
So if you want to test rudimentary, you can do these two regexes:
^a:\d+:{.*?}$
And
^o:\d+:"[a-z0-9_]+":\d+:{.*?}$
for arrays and objects respectively.
Note that this just checks for the generic form. To tell if it's a valid serialized string, you need to run it through unserialize()
and test the return is_array($result)
and is_object($result)
...
精彩评论