This is a function to truncate a string of text while preserving the whitespace (for instance, getting an excerpt from an article while maintaining newlines). It will not jive well with HTML, of course.
<?php
/**
* Truncates a string of text by word count
* @param string $text The text to truncate
* @param int $max_words The maximum number of words
* @return string The truncated text
*/
function limit_words ($text, $max_words) {
$split = preg_split('/(\s+)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
$truncated = '';
for ($i = 0; $i < min(count($split), $max_words*2); $i += 2) {
$truncated .= $split[$i].$split[$i+1];
}
return trim($truncated);
}
?>