rss
twitter
    Made it to the hotel. Where is everyone?

Older Code Samples Fixed...All Hail Regular Expressions

As I mentioned here, there was a problem displaying code samples on some older blog posts. I initially thought the issue stemmed from the fact that I started using a different 'engine' to render the code samples, however, while I think that was part of the problem, I think there was a bigger issue.

When I started to really investigate this issue today (and with the help of my good friends Todd Sharp and Ray Camden...and yes, I did just do some big time 'name dropping') I realized that a big part of the problem was that I switched from Microsoft SQL Server to MySQL as the backend for the blog a few months back - coincidentally, around the same time this issue with the code samples was first noticed (Todd was a huge help in figuring this one out).

The fix was simple, figure out what these extra characters were and use Replace() to strip them out. Once I figured out what these extra characters were, it was real easy to get rid of them

view plain print about
1<cfset data = Replace(data, chr(160), "", "ALL") />

The only problem here was that now, all the code was left aligned, and I lost any indentation that may have existed before. I tried several different things, such as replacing chr(160) with a space (but we all know browsers ignore multiple consecutive spaces), I even tried replacing chr(160) with '&nbsp;', but what happened then was that code rendering engine would display this as text rather than a 'non-breaking space'. Finally, Ray suggested that I replace chr(160) with a 'tab' (since the code rendering engine would take tabs into account. That was a real simple change to my code.

view plain print about
1<cfset data = Replace(data, chr(160), chr(9), "ALL") />

This kind of worked. My older code samples were now indented, but they were indented way too much. Some lines of code would render in the middle of the page. What was happening was that on some lines there could be 2, 3 or more consecutive instances of chr(160), which were being replaced by tabs - lots of white space going on...too much. This is where the regular expressions come in. After some tinkering, I decided that what I needed to do was replace up to 4 consecutive instances of chr(160) with a tab - to match the default width of a tab in some text editors. Thankfully, this is very easy to do with regular expressions.

view plain print about
1<cfset data = REReplace(data, Chr(160)&"{1,4}", Chr(9), "ALL") />

This basically tells ColdFusion to replace 1-4 consecutive occurrences of chr(160) with one tab. If there were 5 consecutive occurrences, this script adds 2 tabs.

The older code samples are not perfect, but they look a lot better, and they look good enough for me not to have to worry about them anymore.

Related Blog Entries

0 comments

(Comment Moderation is enabled. Your comment will not appear until approved.)