What are some common pitfalls to avoid when using substr() in PHP to truncate text and add ellipsis (...) at the end?

One common pitfall when using substr() in PHP to truncate text and add ellipsis (...) at the end is not accounting for the length of the ellipsis itself, which can result in the truncated text being longer than expected. To solve this issue, subtract the length of the ellipsis from the desired length before using substr(). Additionally, make sure to handle cases where the text is shorter than the desired length to avoid errors.

function truncateText($text, $maxLength) {
    $ellipsis = '...';
    if(strlen($text) > $maxLength) {
        return substr($text, 0, $maxLength - strlen($ellipsis)) . $ellipsis;
    } else {
        return $text;
    }
}

// Example usage
$text = "This is a long text that needs to be truncated.";
$truncatedText = truncateText($text, 20);
echo $truncatedText;