Truncate string with ellipses with PHP

We previously discussed how to calculate the length of a string in PHP and I
made mention that using that function is how you would go about truncating a
string if it’s over a specific length. I also said that down the road I would
discuss the topic at hand, truncating a string with ellipses. Here is a pretty
simple function to do just that:

function truncate($string, $length) {
    if (strlen($string) > $length) {
        $string = substr($string, 0, $length) . '...';
    }

    return $string;
}
PHP

Not much to it, right? Here’s a more advanced method that expands the
functionality a bit to allow you control the output. It takes a third argument
that tells it that you want an HTML output instead of just plain ASCII text:

function truncate($string, $length, $html = true) {
    if (strlen($string) > $length) {
        if ($html) {
            // Grabs the original and escapes any quotes
            $original = str_replace('"', '"', $string);
        }

        // Truncates the string
        $string = substr($string, 0, $length);

        // Appends ellipses and optionally wraps in a hoverable span
        if ($html) {
            $string = '<span title="' . $original . '">' . $string . '…</span>';
        } else {
            $string .= '...';
        }
    }

    return $string;
}
PHP

You could definitely take this further by adding another argument to control
the wrapping span. You could also change up the logic to ensure the resulting
output is exactly the passed length instead of the length plus 3 additional
characters for the ....

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.