MIKESTOWE.COM

you are here

Trim Sentence based on Max Characters

Here’s a simple function to trim sentences based on a number of characters (instead of just words) to return the max number of consecutive words possible without exceeding the maximum characters.

function subtext($input,$max_chars) {
$return = array();
$text = explode(‘ ‘,$input);
for($i=0,$t=0; $i < count($text); $i++) {
$t += strlen($text[$i])+1;
if($t <= ($max_chars+1)) {
$return[] = $text[$i];
} else {
break;
}
}
return implode(‘ ‘,$return);
}

Example:
subtext(‘This is an example of this function’,20); returns “This is an example”

Share this Page:
Facebook Twitter Linkedin Reddit Tumblr Email

Leave a Reply

Your email address will not be published. Required fields are marked *