Truncate String to Given Length and Add Ellipsis if Necessary using PHP

mbstring extension

  1. Enable extension in php.ini file:
extension=mbstring
  1. Truncate a string to given length and add ellipsis if necessary:
<?php

function truncateString(string $strInput, int $maxLength): string
{
    return mb_strimwidth($strInput, 0, $maxLength, '...');
}

$text = 'Hello world';
echo truncateString($text, 10).PHP_EOL; // Hello w...
echo truncateString($text, 11).PHP_EOL; // Hello world

Leave a Comment

Cancel reply

Your email address will not be published.