带有PHP 7的可折叠print_r()树(不带preg_replace()和/ e)

时间:2019-01-03 08:27:09

标签: arrays tree preg-replace preg-replace-callback collapsable

为了print_r可折叠的树,我目前正在使用他的代码,该代码使用preg_replace()/e修饰符,该修饰符在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";
}
?>

为了修复它,我尝试了此解决方案Preg replace deprecated, attempting to fix 但它不起作用。 (是的,我认识到该函数中缺少“;”)。 由于-由于缺乏“信​​誉”分数-我无法在此处发表评论,因此我想在这里获得答案...

这是链接中第二个$ out的建议解决方案:

$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 个答案:

答案 0 :(得分:0)

您需要连接变量$ id值,请尝试以下操作:

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