Learning never exhausts the mind
Home >  Coding > PHP > How to Add Three Dots to a Long String with PHP

Published 20th April 2009 by

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:

$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:

function add3dots($string, $repl, $limit) 
  if(strlen($string) > $limit) 
    return substr($string, 0, $limit) . $repl; 
    return $string;
4 thoughts on “How to Add Three Dots to a Long String with PHP
  • 6th November 2020 at 8:48 am

    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

  • 4th May 2020 at 8:26 am

    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.

  • Dr.Ferrous
    6th April 2016 at 12:00 am

    Better shortcut  :) 

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

  • 5th November 2010 at 12:00 am

    A handy shortcut:

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


Leave a Reply

Fields marked with * are mandatory.

We respect your privacy, and will not make your email public. Hashed email address may be checked against Gravatar service to retrieve avatars. This site uses Akismet to reduce spam. Learn how your comment data is processed.