问题
Is there some reliable way to find out whether a string variable is just a string or a string representation of a serialized object/array?
回答1:
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)...
回答2:
You can call unserialize(string $str) function: it returns false, if string cannot be unserialized.
来源:https://stackoverflow.com/questions/4748795/how-to-find-out-if-a-string-is-a-serialized-object-array-or-just-a-string