Solved

Reverse print_r result

Posted on 2014-02-14
4
595 Views
Last Modified: 2016-10-13
Ive got a string contiaing the results from a print_r by using:-
     $myDump = print_r($_SERVER,true);

Open in new window


However now I need to convert $myDump back into an Array, so something like:-
     $myArray = toArray($myDump);

Open in new window


So in the end $myArray should be an exact replica of what $_Server was when I issues print_r ????

So my question is any ideas how I can convert the string

Array
(
    [radQ1] => Yes
    [radQ1_Comments] => Comments...
)
to an array?
0
Comment
Question by:tonelm54
  • 2
4 Comments
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39858672
Just use the $_SERVER array! You haven't changed it.

If you need to save the $_SERVER array for later, then just save that in a variable:

$myServerArray = $_SERVER;
$myDump = print_r($myServerArray, true);
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39858755
If you need to save the $_SERVER array for later,
... then you have a very funky code smell!  In fact, you have a code stench.

But I expect the question is not really about $_SERVER, but about any general print_r() output -- can it be un-munged and turned into the original data set?  I've wondered about this myself since many questions here at EE contain the output of print_r() as a representation of the test data, and I have often had to spend some time converting that back into a PHP variable.

I found this "script kiddie hack" example some time ago and put it into my untested library.  It looked interesting, but I have never tried to document or test it.  It might provide a germ of an idea.  I believe it is supposed to reverse var_dump() output which seems feasible.  It would be harder, I think, to reverse print_r() because you do not have all of the data type representations and would have to make some assumptions.

<?php // RAY_un_var_dump.php

// UNTESTED

function unvar_dump($str) {
    if (strpos($str, "\n") === false) {
        //Add new lines:
        $regex = array(
            '#(\\[.*?\\]=>)#',
            '#(string\\(|int\\(|float\\(|array\\(|NULL|object\\(|})#',
        );
        $str = preg_replace($regex, "\n\\1", $str);
        $str = trim($str);
    }
    $regex = array(
        '#^\\040*NULL\\040*$#m',
        '#^\\s*array\\((.*?)\\)\\s*{\\s*$#m',
        '#^\\s*string\\((.*?)\\)\\s*(.*?)$#m',
        '#^\\s*int\\((.*?)\\)\\s*$#m',
        '#^\\s*float\\((.*?)\\)\\s*$#m',
        '#^\\s*\[(\\d+)\\]\\s*=>\\s*$#m',
        '#\\s*?\\r?\\n\\s*#m',
    );
    $replace = array(
        'N',
        'a:\\1:{',
        's:\\1:\\2',
        'i:\\1',
        'd:\\1',
        'i:\\1',
        ';'
    );
    $serialized = preg_replace($regex, $replace, $str);
    $func = create_function(
        '$match',
        'return "s:".strlen($match[1]).":\\"".$match[1]."\\"";'
    );
    $serialized = preg_replace_callback(
        '#\\s*\\["(.*?)"\\]\\s*=>#',
        $func,
        $serialized
    );
    $func = create_function(
        '$match',
        'return "O:".strlen($match[1]).":\\"".$match[1]."\\":".$match[2].":{";'
    );
    $serialized = preg_replace_callback(
        '#object\\((.*?)\\).*?\\((\\d+)\\)\\s*{\\s*;#',
        $func,
        $serialized
    );
    $serialized = preg_replace(
        array('#};#', '#{;#'),
        array('}', '{'),
        $serialized
    );

    return unserialize($serialized);
}

Open in new window

0
 
LVL 109

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 39858866
Please see http://www.laprbass.com/RAY_temp_tonelm54.php

This is only a starting point -- it would need a lot of work to deal with things like multidimensional arrays and objects.

<?php // RAY_temp_tonelm54.php
error_reporting(E_ALL);
echo '<pre>';

// THE ORIGINAL PRINT_R() OUTPUT IN A STRING
$str = <<<EOD
Array
(
    [radQ1] => Yes
    [radQ1_Comments] => Comments...
)
EOD;

// SHOW THE STARTING POINT
echo htmlentities($str);
echo PHP_EOL;

// PROCESS EACH LINE OF THE PRINT_R()
$new = array();
$arr = explode(PHP_EOL, $str);
foreach ($arr as $sub)
{
    if (strpos($sub, '['))
    {
        // ISOLATE THE KEY
        preg_match('#\[(.*?)\]#', $sub, $mat);
        $key = $mat[1];

        // AND THE VALUE
        preg_match('#\=\> (.*?)$#', $sub, $mat);
        $val = $mat[1];

        // ADD TO THE ARRAY
        $new[$key] = $val;
    }
}

// WHAT JUST HAPPENED
print_r($new);
echo PHP_EOL;

Open in new window

0
 

Expert Comment

by:Ondrej Letacek
ID: 41841854
Hi,
There is a print_r_reverse function described on http://php.net/manual/en/function.print-r.php
Alternatively, you can look at online tool on https://www.nestforms.com/php-print_r-to-json-online where you can convert the print_r result into the json (which you can import into PHP by json_decode).
1

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
These days socially coordinated efforts have turned into a critical requirement for enterprises.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question