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

眉间皱痕 提交于 2019-12-12 16:49:02

问题


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;\">'"
}

回答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;\">'";
}


来源:https://stackoverflow.com/questions/54018676/collapsable-print-r-tree-with-php-7-w-o-preg-replace-and-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!