table.dicks {
background: dongs;
}
hi
hi
hi!
what's up
in this cell |
and this
one |
more
shit
HERE;
// a function that breaks up a string and performs nl2br() only on parts outside of certain tags.
function smartnl2br($string)
{
if(!is_string($string)) return "";
$tagorder = array(array("table", false), array("td", true), array("th", true),
array("style", false), array("pre", false)); // add any other tags you can think of. the booleans accompanying each tag specify whether to nl2br() inside that tag.
$work = array(array($string, true)); // have an array of arrays of strings and booleans. the booleans will determine whether we nl2br() each piece.
foreach($tagorder as $tag) // step through each untouchable tag
{
foreach($work as $key => $str) // step through each piece of the string so far. we need the key so we can splice in the broken-up pieces later.
{
$pieces = preg_split("/(<{$tag[0]}[^>]*>.*?<\/{$tag[0]}>)/is", $str[0], -1, PREG_SPLIT_DELIM_CAPTURE); // split the string up into pieces surrounded by $tag and pieces not surrounded.
if(count($pieces) > 1) // if count is 1, we didn't split it. no need to do more work.
{
$splice = array(); // make a little array to replace the original element
foreach($pieces as $piece) // now step through the preg_split pieces and fill $splice with the appropriate values
{
if(preg_match("/^<{$tag[0]}[^>]*>.*<\/{$tag[0]}>$/is", $piece))
$splice[] = array($piece, $tag[1]);
else $splice[] = array($piece, $str[1]);
}
array_splice($work, $key, 1, $splice); // now splice in the little array where there used to be just the one element
}
}
}
$output = ""; // start building an output string
foreach($work as $piece) // step through the completed array
{
if($piece[1]) $output .= nl2br($piece[0]);
else $output .= $piece[0];
}
return $output;
}
echo smartnl2br($test);
?>