This is a useful script for anybody who wishes to get the beginning of a string up to the word break before $num of characters. Usually the use of substr will break half way through a word and leave things looking a little untidy on your site. This little function allows you to set the maximum length of the string, then it returns all the whole words before it. If the supplied string is shorter than the maximum length, the whole string is returned.
<?php
/**
*
* @break a string at the end of the last word
* before $maxlength chars
*
* @param string $string
*
* @param int $maxlength
*
* @return string
*
*/
function wordbreak($string, $maxlength)
{
$string = substr($string, 0, $maxlength);
return substr($string, 0, strrpos($string, ” “));
}/*** example usage ***/
$string = ‘Heather is hoping to hop to Tahiti to hack a hibiscus to hang on her hat.
Now heather has hundreds of hats on her hat rack, so how can a hop to Tahiti top that?’;echo wordbreak($string, 50).’ …’;
?>