Search code examples
phphtmlpreg-replace-callback

How to automatically convert the tabs in the pasted code(from .net, netbeans, notepad,sublime) to nbsp; in php


So I have this blog which I wrote in php where I post articles regarding programming and embedded systems, its not so famous but I am doing this in a hope that it will serve as a leverage in interviews, I am in final year of college.

I used to contribute to mediawiki and I got inspired by the wikilanguage so I built myself a wikilanguage look-a-like

And in this language when ever I had code to paste in my blog I would surround the code with a tag

I code in a variety of languages hence I end up using a variety of IDE's I have used netbeans, .net studio, notepad, sublime, gedit etc..

private     function makecode($matches){
                $i=0;
                $out = '</br></br><div id = "cod"><table border = 0 width = 600px cellspacing = 0px> <tr></tr>';
                $matcha = htmlspecialchars(($matches[1]));
                                preg_replace("/\t/", "&nbsp;&nbsp;&nbsp;&nbsp;", $matcha);
                $lines = explode("\n", $matcha);

                foreach($lines as $line){
                    if(preg_match('/^\s*#/',$line)){
                        $out .= "<tr><td><font color = \"grey\"><i><small>$line</small></i></font></td></tr>";
                        continue;
                    }
                    if(preg_match('/^\s*$/',$line))continue;
                    $i++;
                    $out .= "<tr><td><small>$i</small>. $line</td></tr>";
            }
                $out .= "</table></div>";

                return $out;
        }

private function coder(){
        $this->text = preg_replace_callback('/<c>(.*?)<cc>/s', array($this,'makecode'),$this->text);

            }

Here's my code for manipulating the code tag.

right now am trying pasting code from notepad and I am replacing the \t with 4 nbsp; assuming that most of the ide's represent there tabs with a '\t' could anyone suggest me a more elegant way of handling the tabs. I do not want to use a ready made library for this.


Solution

  • What about using this ?

    private function makecode($matches) {
        return '<pre>'.htmlspecialchars($matches[1]).'</pre>';
    }
    

    And you can set the tab size with css :

    pre {
        -moz-tab-size:    4;
        -o-tab-size:      4;
        -webkit-tab-size: 4;
        -ms-tab-size:     4;
        tab-size:         4;
    }
    

    EDIT : My mistake, I haven't seen that you need lines numbers ...