可折叠的print_r()树与PHP 7(不带preg_replace()和/e) [英] Collapsable print_r() tree with PHP 7 (w/o preg_replace() and /e)

查看:105
本文介绍了可折叠的print_r()树与PHP 7(不带preg_replace()和/e)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了print_r可折叠的树,我目前正在使用他的代码,该代码使用preg_replace()/e修饰符,在PHP7中已弃用:

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";
}
?>

为了修复它,我尝试了以下解决方案不建议使用Preg替换,试图进行修复 但它不起作用. (是的,我认识到该函数中缺少;"). 由于-由于缺乏信​​誉"分数-我无法在此处发表评论,因此我想在这里获得答案...

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...

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

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

推荐答案

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

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

这篇关于可折叠的print_r()树与PHP 7(不带preg_replace()和/e)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆