Treehouse: Grow your CSS skills. Land your dream job.

Last updated on:

Options to Truncate Strings

Technique #1: Simple

function myTruncate($string, $limit, $break=".", $pad="...") {
        if(strlen($string) <= $limit) return $string; 
        if(false !== ($breakpoint = strpos($string, $break, $limit))) { 
            if($breakpoint < strlen($string) - 1) { 
                $string = substr($string, 0, $breakpoint) . $pad; } 
            } return $string; 
}

Technique #2: Simple

function ellipsis($text, $max=100, $append='&hellip;') {
       if (strlen($text) <= $max) return $text;
       $out = substr($text,0,$max);
       if (strpos($text,' ') === FALSE) return $out.$append;
       return preg_replace('/\w+$/','',$out).$append;
}

Usage:

<?php
$text = "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.";
echo ellipsis($text,100);
?>

Technique #3: More Options

Options to use PHP's php_tidy to fix up broken HTML, or to strip HTML entirely.

function summarise( $input, $break = " ", $end_text = "...", $limit = 255, $tidy_html = 1, $strip_html = 0 ) {
               if ( strlen( $input ) >= $limit ) {
                       $breakpoint = strpos( $input, $break, $limit );
                       $input = substr( $input, 0, $breakpoint ) . $end_text;
               }
               if ( $tidy_html == 1 ) {
                       ob_start(  );
                       $tidy = new tidy;
                       $config = array( 'indent' => true, 'output-xhtml' => true, 'wrap' => 200, 'clean' => true, 'show-body-only' => true );
                       $tidy->parseString( $input, $config, 'utf8' );
                       $tidy->cleanRepair(  );
                       $input = $tidy;
               }
               if ( $strip_html == 1 ) {
                       $input = strip_tags( $input );
               }
               return $input;
}

Technique #4: Without a function

<?php

$long_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$max_length = 40; // we want to show only 40 characters.

if (strlen($long_text) > $max_length)
{
 $short_text = (substr($long_text,0,$max_length-1)); // make it $max_length chars long
 $short_text .= "..."; // add an ellipses ... at the end
 $short_text .= "<a href='http://example.com/page.html'>Read more</a>"; // add a link
 echo $short_text;
}
else
{
// string is already less than $max_length, so display the string as is
echo $long_text;
}

?>

Reference URL

Comments

  1. Simon

    I’m using

    <?php the_tags('','',''); ?>

    to output tags. But where I keep it in my theme it may break if it’s a really long tag. How can I keep the single tags under a certain amount of letters and add ellipses at the end?

    • Chris Coyier

      Looks like that is a WordPress function. You might want to try using get_the_tags() instead of the_tags(). The Get version will return an array instead of echoing the results. Then you can truncate the strings in the array before outputting.

    • Davide Liverino
      Permalink to comment#

      Ciao Simon, Sorry for the unconventional point of contact. I just wanted to say that if you look for Belvedere Villa Mezzomonte on HomeAway and you contact me there, you don’t have to pay guests fees, which should cut a good 10% off your rate. Thanks, Davide

  2. Simon

    Thanks I’ll try that. Very helpful!

  3. Dave
    Permalink to comment#

    Used the first one :)

    Thanks, very helpful

  4. Chris
    Permalink to comment#

    I stopped reading when i saw

    if(false !==

  5. Arelthia
    Permalink to comment#

    Thanks, Chris.

    I used Technique #2: Simple in a plugin to show a brief description about all the bloggers in the sidebar.

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```