How to Change print_r button name using javascript

99 Views Asked by At

I have a code i directly copied from php documentation site. The code enables me to print "print_r" function in a readable format. The code is below

    function print_r_tree($data){
    // capture the output of print_r
    $out = print_r($data, true);

    // replace something like '[element] => <newline> (' with <a href="javascript:toggleDisplay('...');">...</a><div id="..." style="display: none;">

        $out = preg_replace('/([ \t]*)(\[[^\]]+\][ \t]*\=\>[ \t]*[a-z0-9 \t_]+)\n[ \t]*\(/iUe',
    "'\\1<button onClick=\"javascript:toggleDisplay(\''.(\$id = substr(md5(rand().'\\0'), 0, 7)).'\');\">
            \\2 
             </button><div id=\"'.\$id.'\" style=\"display: none;\">'",
        $out);

    // replace ')' on its own on a new line (surrounded by whitespace is ok) with '</div>
    $out = preg_replace('/^\s*\)\s*$/m', '</div>', $out);

    // print the javascript function toggleDisplay() and then the transformed output
    echo '<script language="Javascript">function toggleDisplay(id) { document.getElementById(id).style.display = (document.getElementById(id).style.display == "block") ? "none" : "block"; }</script>'."\n<pre>$out</pre>";
}

The Code above output three buttons like [ [0] => Array ], [ [1] => Array ] and [ [2] => Array ]. But I want the button to be outputted in the Following format [Good], [Average], and [Worst]. I have tried to change the "\2" in the text on the button to the JavaScript snippet below

$out = preg_replace('/([ \t]*)(\[[^\]]+\][ \t]*\=\>[ \t]*[a-z0-9 \t_]+)\n[ \t]*\(/iUe',
    "'\\1<button onClick=\"javascript:toggleDisplay(\''.(\$id = substr(md5(rand().'\\0'), 0, 7)).'\');\">
//Writing Javascript code to display buttons instead of "//2"
            <script type= \"text/javascript\">
            var behaviours = new array('Good', 'Average', 'Worst');
            for(var i = 0; i < behaviours.length; i++)
            document.write(behaviours[i]);
            </script>           

             </button><div id=\"'.\$id.'\" style=\"display: none;\">'",
        $out);

But it is giving me regex and identifier errors. What can I do about this please.

1

There are 1 best solutions below

0
On

Blindly copying some random code snippet from a php.net documentation comment isn't a good approach on anything. Especially if you apparently don't know what you're doing. Understand what you're doing.

That being said. Why not change the $data array before it is print_r'ed?

$data = ['Good' => $data[0], 'Average' => $data[1], 'Worst' => $data[2]];