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

Is there any reliable way to find out if a string variable is just a string or string representation of a serialized object / array?

+2
source share
2 answers

Well, you can tell by looking at the format. When you serialize the array, you get a line that looks like a:1:{i:0;s:3:"foo"} And if you serialize the object, you get: o:7:"myclass":1:{s:3:"foo";s:3:"bar";} .

So, if you want to test the rudimentary, you can execute these two regular expressions:

 ^a:\d+:{.*?}$ 

and

 ^o:\d+:"[a-z0-9_]+":\d+:{.*?}$ 

for arrays and objects respectively.

Please note that this just checks the general form. To find out if this is a valid sequential string, you need to run it through unserialize() and check the inverse of is_array($result) and is_object($result) ...

+4
source

You can call unserialize(string $str) : it returns false if the string cannot be unserialized.

+7
source

Source: https://habr.com/ru/post/944444/


All Articles