PHP / mySQL Jump to comments
I couldn't find any helper for CakePHP to implement GeSHi, so I had to write my own. Bellow are the results of this helper in action.

To be able to use this helper you need to download GeSHi and put it in /app/vendors/geshi directory. You only need geshi.php and the geshi folder.

/app/views/helpers/formatting.php
  1. <?php
  2. App::import('Vendor','geshi'.DS.'geshi');
  3.  
  4. class FormattingHelper extends Helper{
  5. function parse_code($code){
  6. $code=@preg_replace("#<code(.*?)>(.*?)</code>#s","\\2",$code);
  7. if($code[1]=="") $language="php";
  8. else $language=@preg_replace("#language=\"(.*?)\"#s","\\1",$code[1]);
  9. $geshi=new GeSHi(html_entity_decode(trim($code[0])),$language);
  10. $geshi->set_header_type(GESHI_HEADER_PRE);
  11. $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS);
  12. $geshi->start_line_numbers_at(1);
  13.  
  14. return $geshi->parse_code();
  15. }
  16.  
  17. function geshi($text){
  18. $geshi=@preg_replace_callback("#<code(.*?)>(.*?)</code>#s",Array($this,"parse_code"),$text);
  19.  
  20. return $geshi;
  21. }
  22. }
  23. ?>

Load the helper into your cotroller var $helpers=Array('Formatting');. To tell the helper what to highlight, the text from your view must be between the <code></code> tags. You can specify the language you wish to highlight like this: <code language="php"></code>. If no language is defined, the default language is set to php.

For example:
  1. <?php
  2. $text='<code language="php">';
  3. $text.='echo\'Hello world! \';';
  4. $text.='for($i=0;$i<10;$i++){ echo $i; }';
  5. $text.='</code>';
  6.  
  7. echo $formatting->geshi($text);
  8. ?>

The results are similar to this page and should work without any problems. This helper is highlighting only php code. It can be extended for any type of language.

Enjoy!

6 comments so far

  1. gravatar
    # 1
    Ryatzu
    March 3rd, 2008 at 09:23:52

    Thank you, it works great.
    Im only trying to get it work with TinyMCE but it seems that TinyMCE converts everything to normal html even if i change the html myself. I tried editing the .js file but it got way to much line and im not an expert, maybe you know a solution?

  2. gravatar
    # 2
    Ryatzu
    March 3rd, 2008 at 09:42:33

    To get it work with TinyMCE change the <code> tag to <pre> in /app/views/helpers/formatting.php

    Thats it.

  3. gravatar
    # 3
    gurde
    March 3rd, 2008 at 11:53:50

    @Ryatzu: Instead of putting in your <code> html tags, use &lt; for < and &gt; for >.

  4. gravatar
    # 4
    roryy
    March 3rd, 2008 at 18:55:33

    thanks Gurde, I can use this :)

  5. gravatar
    # 5
    Scott Sanders
    March 20th, 2008 at 15:38:42

    This works very well, and is definitely going to be useful in my projects. Many thanks!

  6. gravatar
    # 6
    gurde
    March 29th, 2008 at 07:24:44

    @Scott Sanders: I am pleased to know it's useful for somebody.

Post your comment