Learning never exhausts the mind

Published on 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; 
  }
  else 
  {
    return $string;
  }
}
2 thoughts on “How to Add Three Dots to a Long String with PHP
  • Dr.Ferrous
    6th April 2016 at 12:00 am

    Better shortcut  :) 

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

    Reply
  • 5th November 2010 at 12:00 am

    A handy shortcut:

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

    Reply

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.