替代在博客中准备和显示代码示例

I was doing a little blog using TinyMCE and PHP/MySql to proccess / store the data. I've done it several times before, but in this one I wanted to write blocks of example code with <pre></pre> tags. The problem was to write the html code, I needed to replace the < and > of the code I wanted to display for &lt; and &gt;

I didn't find a way to configure TinyMCE to do it, so I made a little js to replace and paste my code examples:

$("#change").click(function(){
  var output = $("#source").val().replace(/</g,"&lt;");
  output = output.replace(/>/g,"&gt;");
  $("#output").val("<pre>"+output+"</pre>");
});

It worked to insert the string in the database one time, but I found out that when I wanted to update it the entities where changed again after displaying them in the textarea. So, to update to the database I needed to replace again the characters of the piece of string.

So I wrote this little function to prepare the string to insert in the db with PHP:

function processCode($string_raw,$start,$end) {
    if(preg_match_all("/".$start."(.*?)".str_replace("/","\/",$end)."/s",$string_raw,$matches)) {

        for($i=0 ; $i<count($matches[0]) ; $i++) {
            $processed = htmlentities($matches[1][$i]);
            $string_raw = str_replace(  $matches[0][$i], 
                                        $start.$processed.$end, 
                                        $string_raw);
        }
    }
    return $string_raw;
}

It takes a string like:

$raw_string = "This code <pre><b>code</b></pre> is mine";

And replaces the entities inside the $star and $end tags.

It works great, to insert and update, but I'm still wondering:

  • Is there a way to configure TinyMCE to do this?
  • Is there an easier / gentler way to solve it?
  • Am I missing anything important?

PD: and if you think of a better title for the question, please let me now it :)

TinyMCE has a codesample plugin designed specifically to allow people to insert code samples into their content:

https://www.tinymce.com/docs/plugins/codesample/

If you use this you don't need all that code to to process a paste and wrap it in <pre> tags.