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:

<?php

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

Watch a course Learn object oriented PHP

You can then use the function as follows:

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