W3docs

Truncate a string to first n characters of a string and add three dots if any characters are removed

To truncate a string to the first n characters and add three dots if any characters are removed in PHP, you can use the following function.

To truncate a string to the first n characters and add three dots if any characters are removed in PHP, you can use the following function:

How to truncate a string to the first n characters and add three dots if any characters are removed in PHP?

<?php

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

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

You can then use the function as follows:

Example of truncating a string to the first n characters and adding three dots if any characters are removed in PHP

<?php

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

$string = 'This is a long string';
echo truncate($string, 10);  // Outputs: "This is ..."
echo truncate($string, 20);  // Outputs: "This is a long string"

The function first checks if the length of the string is greater than the desired length. If it is, it returns a truncated version of the string with three dots appended to the end. Otherwise, it returns the original string.