如何确定字符串是序列化对象/数组还是只是字符串? [英] 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 string representation of a serialized object/array?
推荐答案
嗯,看格式就知道了.当你序列化一个数组时,你会得到一个看起来像 a:1:{i:0;s:3:"foo"}
的字符串,如果你序列化一个对象,你会得到:o:7:"myclass":1:{s:3:"foo";s:3:"bar";}
.
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+:{.*?}$
和
^o:\d+:"[a-z0-9_]+":\d+:{.*?}$
分别用于数组和对象.
请注意,这只是检查通用表单.要判断它是否是有效的序列化字符串,您需要通过 unserialize()
运行它并测试返回 is_array($result)
和 is_object($result)
...
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)
...
这篇关于如何确定字符串是序列化对象/数组还是只是字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!