The UHF of the film world.


quietearth [General News 11.11.06]

Share on Google+


Displaying code properly, especially in your blog, is a pain. The main problem is how to display spaces and tabs properly. We have a few options:

1. Use html markup like the "pre" tag which will properly display it.
2. If you are using php, you can use the highlight_file (or highlight_string) functions. This uses the "code" tag with some preformatted colors and puts in the spaces for you. More on this and changing the default colors is available on the function page.
3. The one I use. I also do the same thing as the highlight* functions in php, but I just add my own spaces.


function htmlrep($str) {
        $x1 = array("&", "<", ">", "\"");
        $x2 = array("&", "<", ">", """);
        return(str_replace($x1, $x2, $str));
        }

function code_callback($matches) {
        $str = ereg_replace(" ", "&nbsp;", $matches[0]);
        return($str);
        }

function code_replace($str) {
        $newstr = htmlrep($str);
        $newstr = preg_replace_callback("/(\s{2,})/", "code_callback", $newstr);       
        return $newstr;
        }


The htmlrep function makes sure any examples of html we have are escaped properly. Now all we need to do is run code_replace on the text, and it will add in the appropriate amount of spaces. If you were to write a blog post that had the "code" tag intermixed with the posting, juse use a preg_split on both the open and close code tags.


Leave a comment








Related articles