Ok, it ain't pretty, but it works.
<?php
$msgBody = 'This is a
test for white
space blah blah
more text over here
blah blah';
$inCode = false; // are we in
tags?
$newString = ""; // string we're building
$msgLength = strlen($msgBody); // how many char's are we searching through?
for ($i = 0; $i < $msgLength; $i++)
{
// check to see if we're starting code block
// NOTE: not case sensitive
if (substr($msgBody, $i, 6) == "[code]")
{
$inCode = true;
$newString .= "[code]"; // throw the '[code]' string in and save some unnecessary additional parsing
$i += 6; // increment the counter by the length of the char's we just appended
continue; // go to the next char
}
if ($inCode)
{
// check to see if we should stop searching for whitespace
if (substr($msgBody, $i, 7) == "
")
{
$inCode = false;
$newString .= "[/code]";
$i += 7;
continue;
}
// if we hit here, we're in a code block and have to check for whitespace
$newString .= ($msgBody{$i} == " ") ? "" : "$msgBody[$i]"; // if it's a space, append
// if it's not, append the character as is
}
else
{
// if we get here, we're not in a code block, so just append as is
$newString .= $msgBody{$i};
}
}
echo "$msgBody<BR>";
echo "$newString";
?>
NOTES:
1. This only searches for a space, " " NOT all whitespace as you specified.
2. The search for the
block is case sensitive as the comment mentions. [CODE] or [CoDe] will not cause it to start replacing spaces.
Hope this helps a little anyway.
Adam