我有一个关于在网站上显示的PHP代码(存储在数据库中)的问题。高亮代码从数据库
这是我在数据库中的文本:
Blah Blah Blah this is regular text
[code]
<?php
$message = \"<div class=\'code\' style=\\\"NO\\\">\";
echo $message;
?>
[/code]
Blah Blah Blah this is more regular text
,我想显示为:
Blah Blah Blah this isregular text
<?php
$message = "<div class='code' style=\"NO\">";
echo $message
?>
Blah Blah Blah this is more regular text
现在我所做的是以下几点:
<?php
echo nl2br(highlight(clean_only($post['post'])));
function clean_only($input) {
if(get_magic_quotes_gpc()) {
$return = stripslashes($input);
}
else {
$return = $input;
}
return $return;
}
function highlight($t0) {
return preg_replace('/\[code\](.*?)\[\/code\]/ise',"'<code>'.highlightCode(\"$1\").'</code>'",$t0);
}
function highlightCode($code) {
$source_code = highlight_string($code,true);
$source_code = str_replace(
array('style="color: #0000BB"','style="color: #007700"','style="color: #DD0000"','style="color: #FF8000"','style="color: #000000"'),
array('class="phpdefault"','class="phpkeyword"','class="phpstring"','class="phpcomment"','class="htmldefault"'),
$source_code);
return "<div class='code'><table cellspacing='1' cellpadding='2'><tr><th valign='top'>".implode("<br />",range(1,substr_count($source_code,"<br />")-1))."</th><td valign='top' nowrap='nowrap'>".str_replace("<code><span class=\"htmldefault\"><br />","<code><span class=\"htmldefault\">",preg_replace("/[\n\r]/","",$source_code))."</td></tr></table></div>";
}
?>
出于某种原因,它删除了所有PHP变量,并且还混淆了引号和反斜杠。显然有一些反斜杠需要留在那里,有些需要去。
仅供参考 - 我真的要做到这一点不使用JavaScript,并且不具有将其插入到数据库之前,“过滤器”我的代码输入。
SOLUTION 特别感谢埃米尔·H:
function highlight($t0) {
return preg_replace('/\[code\](.*?)\[\/code\]/ise','"<code>".highlightCode(clean_only(\'$1\'))."</code>"',$t0);
}
你很受欢迎。 :) –
你是一个真棒的家伙!如果我可以不止一次地感谢你,我会! –