2016-01-05 20 views
0

我剛剛升級到PHP 7,並且一直在探索與不推薦使用的函數相關的錯誤,並取得了很大的成功。Preg替代已棄用的,試圖修復

不幸的是,我一直無法修復我的「查看php數組中的交互式可摺疊javascript事物」代碼的新preg替換方法。

下面的代碼:

function print_r_tree($data) 
{ 

// capture the output of $this->print_r_tree 
    $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():不再支持/ e修飾符,請使用preg_replace_callback代替

刪除第一個「preg_replace」中的「e」,會中斷javascript事件。我也嘗試了一些preg_replace_callback的東西。

我一直在嘗試使用此鏈接Replace preg_replace() e modifier with preg_replace_callback來幫助我瞭解什麼是壞的,但我認爲我的問題很複雜的JavaScript。

我希望有人能夠通過這個,我的代碼?

在此先感謝。

+1

您可能會在這裏找到一些幫助:http://stackoverflow.com/questions/21000320/php-preg-replace-alternative –

+0

嗨,想知道你是否設法解決了棄用警告。 –

回答

0

e修飾符在您的第一個$out變量中。要改變這一點,你需要正確preg_replace_callback()使用:

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

看到,在preg_replace_callback我們定義第二個參數與callbackFunction,該字符串被解析到調用該函數,並將其傳遞與匹配的數組。所以替換是callbackFunction()函數,匹配是matches[X]

更多信息:

http://php.net/manual/es/function.preg-replace-callback.php

祝你好運!

相關問題