Truncate string with ellipses with PHP

Josh Sherman
2 min read
Software Development 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;
}

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 . '&hellip;</span>';
        } else {
            $string .= '...';
        }
    }

    return $string;
}

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 ....

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

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.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles