Truncate

By F*U*R*B*Y* on Jun 23, 2008

Been on the Hawkee.com Snippet page and wondered how to get a short description?

(Example Image.)

Image

Well now you can :)

Enjoy :)

<?php

function truncate($string, $del) {
  $len = strlen($string);
  if ($len > $del) {
    $new = substr($string,0,$del)."...";
    return $new;
  }
  else return $string;
}

$arg = "Hello World. How are you?";

echo $arg."n";  // Returns "Hello World. How are you?"
echo truncate($arg, 5)."n";  // Returns "Hello..."
echo truncate($arg, 7)."n";  // Returns "Hello W..."

?>

Comments

Sign in to comment.
bone282   -  Mar 14, 2009

Here's what i use. It doesn't leave any chopped word on the end.
Very handy for long strings..

<?php 
function do_TrimString($string, $MaxSTRLEN = null) {
    if ($MaxSTRLEN == null) { global $MaxSTRLEN; }
    if (strlen($string) > $MaxSTRLEN) {
        $string = substr($string, 0, $MaxSTRLEN);
        $end = strrpos($string, ' ');
        if ($end === false) {
            $end = $MaxSTRLEN;
            }
        $string = substr($string, 0, $end) . '...';
        }
    return $string;
    }
?>
 Respond  
Hawkee   -  Aug 25, 2008

Simple enough and very useful. Don't really need to use "else" before your default return though.

 Respond  
aWoL   -  Jun 25, 2008

Good work as always Furbs ;p

 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.