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

How to Add Three Dots to a Long String with PHP

Truncate long strings with PHP...

Written By on in PHP

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




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

Your email address will not be published.

If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me