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 TrottPHP Tutorials • April 20, 2009
How to Add Three Dots to a Long String with PHP

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;
  }
}

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

My website and its content are free to use without the clutter of adverts, popups, marketing messages or anything else like that. 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 comments. Why not join the discussion!

New comments for this post are currently closed.