On Tue, 01 Jun 2004 20:33:05 GMT, Kent Brewster <ke**@mindsack.com> wrote:
I've got a (large, hairy, evil) database full of raw dumps from MySQL
that look like this:
<code>
+----+----------+
| k | t |
+----+----------+
| 1 | apple |
| 2 | orange |
| 3 | pear |
+----+----------+
3 rows in set (0.00 sec)
</code>
When displayed in HTML, the extra spaces don't show, leaving this:
+----+----------+
| k | t |
+----+----------+
| 1 | apple |
| 2 | orange |
| 3 | pear |
+----+----------+
3 rows in set (0.00 sec)
OK, that's expected.
Using <pre> tags won't work, due to other complications with the way
carriage returns are being automatically converted to <br> tags at the
end of each line.
Can anyone recommend a PHP preg_replace statement that would change all
spaces within <code></code> tags to nonbreaking spaces? (This
seems like it ought to be out there somewhere in dozens of examples; if
it is, please feel free to rub my nose in my failure to RTFM.)
I really want to do this with a regular expression and a bunch of other
crawling around; each data record is already filtered through
preg_replace to pop external links up in new browser windows and so
forth. It would be outstanding if I could just add another find pattern
and another replace pattern to the existing module and be done.
If you've already got newlines sussed, then basically all you want to do is
change any sequence of n spaces (n>1) into a space and (n-1) entities
(if you want to allow longish lines to wrap. If not, then ditch the leading
space and just output n s). Something like (untested):
preg_replace_callback('/( {2,})/',
create_function('$m',
'return " ".str_repeat(" ",strlen($matches[1])-1);'));
If you've got tabs in there, you'll probably want a prior step turning them
into 4 or 8 spaces depending on your preference. Then present the lot in a
monospace font.
Since you only want it between <code> tags, you probably want that function
called as a callback from another preg_replace_callback('/<code>(.*?)<\/code>',
....). At which point you're probably better of ditching the create_function's
and just making them ordinary functions (I tend to overuse create_function as I
think in Perl for this sort of thing, where anonymous subs have much cleaner
syntax).
So something vaguely like:
function munch_spaces($matches)
{
return ' '.str_repeat(' ', strlen($matches[1]) - 1);
}
function crunch_code($matches)
{
return preg_replace_callback(
'/( {2,})/',
'munch_spaces',
$matches[1]
);
}
preg_replace_callback(
'/<code>(.*?)<\/code>/',
'crunch_code',
$large_hairy_evil
);
--
Andy Hassall <an**@andyh.co.uk> / Space: disk usage analysis tool
http://www.andyh.co.uk /
http://www.andyhsoftware.co.uk/space