Web Design that taps into the haromny and vision of your dreams.

How to Add Three Dots to a Long String with PHP

By on in Coding

91 words, estimated reading time 1 minutes.

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;

Last updated on: Wednesday 21st June 2017



Have a question or suggestion? Please leave a comment to start the discussion.



Better shortcut :)

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

Reply to Dr.Ferrous
Jeroen Haan

Jeroen Haan

A handy shortcut:

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

Reply to Jeroen Haan


Leave a Reply

Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Your email address will not be published.