2017-09-01 99 views
0

我有一个直接从php documentation site复制的代码。该代码使我能够以可读格式打印“print_r”功能。代码如下如何使用javascript更改print_r按钮名称

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

上面的代码输出三个按钮,如[ [0] => Array ], [ [1] => Array ] and [ [2] => Array ]。 但我希望按以下格式输出按钮[Good], [Average], and [Worst]。我试图在文本上的按钮来更改“\ 2”的JavaScript代码段下面

$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); 

但它给我的正则表达式和标识错误。我能做些什么呢。

回答

0

从php.net文档注释中盲目地复制一些随机代码片段并不是一个很好的方法。特别是如果你显然不知道你在做什么。了解你在做什么。

这就是说。为什么不在print_r'ed之前更改$data阵列?

$data = ['Good' => $data[0], 'Average' => $data[1], 'Worst' => $data[2]]; 
相关问题