PHP PHP String Compact Function

Learn how to use the PHP stringCompact function to compact a string to a specified length.

function stringCompact($str, $length = 0)
{
    if ($length === 0 || mb_strwidth($str) <= $length) {
        return $str;
    }

    return mb_strimwidth($str, 0, $length, '...');
}