Collapsable print_r() tree with PHP 7 (w/o preg_replace() and /e)
Asked Answered
S

1

2

In order to print_r a collapsable tree, I'm currently using his code which uses preg_replace() and the /e modifier, which is depreciated in PHP7:

<?php
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<a href=\"javascript:toggleDisplay(\''.(\$id = substr(md5(rand().'\\0'), 0, 7)).'\');\">\\2</a><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$out";
}
?>

In order to fix it, I tried this solution Preg replace deprecated, attempting to fix but it's not working. (Yes, I recognized the ';' is missing in the function there). Since - due to lack of 'reputation' points - I can't comment there, I'm trying to get an answer here...

This is the unchanged proposed solution for 2nd $out in the link:

$out = preg_replace_callback('/([ \t]*)(\[[^\]]+\][ \t]*\=\>[ \t]*[a-z0-9 \t_]+)\n[ \t]*\(/iU', "callbackFunction", $out);

function callbackFunction($matches) {
     return "'".$matches[1]."<a href=\"javascript:toggleDisplay(\''.(\$id = substr(md5(rand().'".$matches[0]."'), 0, 7)).'\');\">".$matches[2]."</a><div id=\"'.\$id.'\" style=\"display: none;\">'"
}
Sundin answered 3/1, 2019 at 8:27 Comment(0)
O
1

You need to concat the variable $id value, try this:

function callbackFunction($matches) {
    $id = substr(md5(rand().$matches[0]), 0, 7);
    return "$matches[1]<a href=\"javascript:toggleDisplay('$id');\">$matches[2]</a><div id='$id' style=\"display: none;\">'";
}
Osteoclast answered 25/2, 2019 at 21:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.