How to find out if a string is a serialized object/array or just a string?

℡╲_俬逩灬. 提交于 2019-12-22 17:44:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!