Thursday, September 30, 2010

Trim a string up to character limit without word cut in PHP

Lots of times when you're developing a site, you'll want to have a snippet of text in one place. PHP doesn't really have a good way of doing this because different languages have different definitions of "words", and a space-character is not always the delimiter between words, as it is in most Latin-based languages.

But for those of us speaking languages that stick spaces between words, clients will often ask us to "just show the first 10 words" here or there. So here's a handy PHP function to do just that.

This function can be used to trim a long string up to a given character limit/count without the last word not being cut half.



function trim_me($content, $limit){

$content = substr($content, 0,$limit);
 
$wordlimit = 1000;

$content = explode(' ',$content);

for($i=0; $i<$wordlimit; $i++) $summary[$i] = $content[$i];

$summary = implode(' ', $summary).'...';

return $summary;

}

?>

Sample Usage:

trim_me($sample_string,10);

No comments:

Popular Posts