วันพุธที่ 8 ธันวาคม พ.ศ. 2553

replace bbcode to syntaxhighlighter


<?php
function view($t){
$br = '<!--x-->';
$t = str_replace(array("\r\n","\r","\n"),$br,htmlspecialchars($t));
$sr = array(
'/\[php\](.*?)\[\/php]/is' => '<pre class="brush: php;">%s</pre>',
'/\[js\](.*?)\[\/js]/is' => '<pre class="brush: js;" >%s</pre>',
'/\[html\](.*?)\[\/html]/is' => '<pre class="brush: html;" >%s</pre>',
);
foreach($sr as $s => $r){
preg_match_all($s, $t, $ms, PREG_SET_ORDER);
foreach($ms as $m) $t = str_replace($m[0], sprintf($r,str_replace($br,"\r\n",$m[1])), $t);
}
$t = str_replace($br,'<br'.'>',$t);
return $t;
}

echo view(
'[php]
<?php echo "test";?>
[/php]
ทดสอบ

ว่าทำงานได้หรือยัง

test
[php] xxx[/php]
[js]var j=1;[/js]
[html]<p>test</p>[/html]'
);

?>

1 ความคิดเห็น: