xiven.com stating the blatantly obvious since 2002

More invalid HTML/XHTML problems

I was just playing around with the highlight_file() function in PHP. Lovely function except it's putting <font> tags in (urrghhh). So after a little playing around I made a little bit of code to sort it out.

The following code will reformat the output from the highlight_file() function into valid XHTML (removes <font> elements, replaces with <span> <code> ). It also makes use of the <pre> tag instead of all those &nbsp; and <br /> tags being in there.

Note: It has since been brought to my attention that using <code> tags is more semantically correct than <span> (thanks David) so the code below has been updated to do just that.

<style type="text/css">
  .source code.html { color: <?=ini_get('highlight.html')?>; }
  .source code.default { color: <?=ini_get('highlight.default')?>; }
  .source code.keyword { color: <?=ini_get('highlight.keyword')?>; }
  .source code.string { color: <?=ini_get('highlight.string')?>; }
  .source code.comment { color: <?=ini_get('highlight.comment')?> }
echo '<pre class="source">';
$source = highlight_file('xxx.php', true);
$search[0] = '<font color="'.ini_get('highlight.html').'">';
$search[1] = '<font color="'.ini_get('highlight.default').'">';
$search[2] = '<font color="'.ini_get('highlight.keyword').'">';
$search[3] = '<font color="'.ini_get('highlight.string').'">';
$search[4] = '<font color="'.ini_get('highlight.comment').'">';
$search[5] = '</font>';
$search[6] = '<br />';
$search[7] = "\r";
$search[8] = '&nbsp;';
$replace[0] = '<code class="html" xml:lang="x-html">';
$replace[1] = '<code class="default" xml:lang="x-php">';
$replace[2] = '<code class="keyword" xml:lang="x-php">';
$replace[3] = '<code class="string" xml:lang="x-php">';
$replace[4] = '<code class="comment" xml:lang="x-php">';
$replace[5] = '</code>';
$replace[6] = "\n";
$replace[7] = '';
$replace[8] = ' ';
echo str_replace($search,$replace,$source);
echo '</pre>';

Yes, some code very much like this was used to make the above listing of the code look nice, and yes, the real reason why I made this post was to test it out... :)

Posted: 2002-12-18 18:03:37 UTC by Xiven | Cross-references (0) | Comments (2)