Trim a String Without Cutting Any Words


Sometimes you need to trim a string without cutting any word.

In PHP there is no any function for that but this function may help you.


function trim_sentence($str, $n, $delim='...'){
$len = strlen($str);
if ($len > $n){
preg_match('/(.{' . $n . '}.*?)\b/', $str, $matches);
return rtrim($matches[1]) . $delim;
}
else {
return $str;
}
}

Advertisements
Posted in PHP

3 thoughts on “Trim a String Without Cutting Any Words

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s