HTML Highlighter

ทำ hilight ได้ 2 ลักษณะ คือ ใช้ BBCode เช่น [php]....[/php] หรือ ทำ highlight เมื่อ อยู่ภายใน สัญลักษณ์ของโค้ด นั้นๆ  เช่น <?....?>

เหตุผลที่ผมเลือกการทำ highlight ให้กับโค้ดแบบนี้ ก็เพราะต้องการแค่จะแยก ส่วนที่เป็นโค้ด ออกจากข้อความปกติเท่านั้น ไม่ได้ต้องการความสวยงามเพอร์เฟ็คแต่อย่างใด และที่สำคัญ ผมต้องการที่จะ เน้น ข้อความที่สำคัญด้วยตัวเอง เพื่อที่จะอธิบาย และทำความเข้าใจได้ง่ายขึ้น

ตัวอย่างก็การทำ highlight ให้กับโค้ดบนเว็บไซต์นี้แหละครับ

ผมใช้ preg_replace เพื่อจับคู่ ส่วนที่เป็นโค้ด ที่อาจเป็น โค้ดจริงๆ หรือ การใช้ BBCode ร่วมกับการกำหนดสีด้วย CSS ซึ่งหากต้องการเปลี่ยนสี ก็สามารถแก้ไขได้ง่ายๆด้วย CSS เท่านั้น

<?
//HTML highlighter
function htmlhighlighter($temp) {
  //script
  $temp = preg_replace ('/(&lt;script(.*?)&gt;(.*?)&lt;\/script&gt;)/is', "<font class=\"script\">\\1</font>", $temp);
  //php
  $temp = preg_replace ('/(&lt;\?(.*?)\?&gt;)/is', "<font class=\"php\">\\1</font>", $temp);
  //asp
  $temp = preg_replace ('/(&lt;%(.*?)%&gt;)/is', "<font class=\"asp\">\\1</font>", $temp);
  //style
  $temp = preg_replace ('/(&lt;style(.*?)&gt;(.*?)&lt;\/style&gt;)/is', "<font class=\"style\">\\1</font>", $temp);
  //comment
  $temp = preg_replace ('/(\/\*(.*?)\*\/)/is', "<font class=\"comment\">\\1</font>", $temp);
  $temp = preg_replace ('#(^|[^:])(//)([^<]+)#sm', "\\1<font class=\"comment\">\\2\\3</font>", $temp);
  $temp = preg_replace ('/(&lt;!--(.*?)--&gt;)/is', "<font class=\"comment\">\\1</font>", $temp);

  //BBCode (html)
  $types='script|php|comment|asp|style|html|xml|sql';
  $temp = preg_replace("/\[($types)\]/", '<font class="\\1">', $temp);
  $temp = preg_replace("/\[\/($types)\]/", "</font>", $temp);
  
return $temp;
}
?>
<style type="text/css">
/* html highlighter */
.script {
  color:#666666;
}
.php {
  color:olive;
}
.comment {
  color:green;
}
.asp {
  color:#FF00FF;
}
.style {
  color:#CC00FF;
}
.html {
  color:teal;
}
.sql {
  color:navy;
}
.xml {
  color:#CC6600;
}
</style>
ผู้เขียน goragod โพสต์เมื่อ 05 มิ.ย. 2552 เปิดดู 12,813 ป้ายกำกับ PHPCSS
^