Today is Sunday
September 5, 2010

June 22, 2010

PHP truncate/shorten string, variable, text

by Chris — Categories: Coding, PHP — Tags: , , No Comments

Every now and again on my projects I come into a spot where I have limited room to display any given amount of text that is generated and updated dynamically. Example I have a length of text thats 400 some odd characters long. I only have room for 120 characters. “So what do I do?” If your asking yourself that question then I have an answer for you, keep in mind not THE answer as there are better solutions out there that will trim truncate any given string down to the number you want but leaving full words in tact at the end rather then cut them off mid word. This function I will show you here that I made for myself a while back is expandable to do such things however I haven’t ran into the need or desire to expand it as such myself as it works for what I use it for without problem.

<?php function ShortenText($text, $chars) {
// Change to the number of characters you want to display
$chars = $chars;
$text = $text."";
$countchars = strlen($text);

if($countchars > $chars) {
$text = substr($text,0,$chars);
$text = substr($text,0,strrpos($text,' '));
$text = $text."...";
}

return $text;
}
$myText = "Welcome to Monkey Tooth Productions.";
echo ShortenText($myText, 20);
?>

Translates to:
Welcome to Monkey…

It automatically appends the “…” to the string so try to remember that if you need 20 max you should set it to 17 however you can change that or remove it even if you like.

Well as with any code I throw up here on the site, if you expand this and improve it let me know. I’d be happy to see what you guys do with it.

No Comments »

No comments yet.

Leave a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© 2010 Monkey Tooth Productions All rights reserved - Wallow theme by TwoBeers Crew - Powered by WordPress - Have fun!