Solved

Reverse print_r result

Posted on 2014-02-14
4
540 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 42

Expert Comment

by:Chris Stanyon
Comment Utility
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 108

Expert Comment

by:Ray Paseur
Comment Utility
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 108

Accepted Solution

by:
Ray Paseur earned 500 total points
Comment Utility
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
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

771 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now