How to Add Three Dots to a Long String with PHP

Here is a simple little function in PHP that will truncate a string after X number of characters and add three dots or whatever you specify.

By Tim Trott | PHP Tutorials | April 20, 2009

Ellipsis are a series of three dots that indicate an intentional omission of a word, sentence or whole section from the original text being quoted. Here is a simple little function in PHP that will truncate a string after X number of characters and replace it with three dots (or whatever you specify). This is useful when showing an excerpt or a short introduction.

$string is the string to truncate, $repl specifies what to replace it with and $limit is how many characters to allow. If $limit is greater than the string length then the string is unchanged.

Example usage:

php
$string = "This is a very long test string that I am using to test long strings";
echo add3dots($string, "...", 12); / Result: "This is a ve..."

The function:

php
function add3dots($string, $repl, $limit) 
{
  if(strlen($string) > $limit) 
  {
    return substr($string, 0, $limit) . $repl; 
  }
  else 
  {
    return $string;
  }
}
Was this article helpful to you?
 

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

This post has 4 comment(s). Why not join the discussion!

We respect your privacy, and will not make your email public. Learn how your comment data is processed.

  1. JS

    On Friday 6th of November 2020, js truncate string said

    thanks for the script! i recently solved this issue on client side by using the js library cuttr.js to truncate a string and adding the three dots - https://github.com/d-e-v-s-k/cuttr-js

  2. LO

    On Monday 4th of May 2020, Louis said

    This is a good shortcut !
    However, as you mentioned in your example this method actually cut a sentance in the middle of the word "very".

    I actually tried to look for solution in order to avoid this issue and found this article that describes how to proceed : https://yoroshikune.com/cut-string-length/

    It seems impossible to avoid this problem without building a kind of custom substring function.

  3. DF

    On Wednesday 6th of April 2016, Dr.Ferrous said

    Better shortcut :)

    mb_strimwidth("Hello World", 0, 10, "...");

  4. JH

    On Friday 5th of November 2010, Jeroen Haan said

    A handy shortcut:

    print (strlen($string) > 24)? substr($string, 0, 24) . "...": $string;