Search the blog

This is how you shorten a string with PHP.

function shortenString($string, $length, $trailingChar = '…') {
    
    if (is_string($string) === false) {
     
        return false;
        
    }

    if (mb_strlen($string) > $length) {

        return mb_substr($string, 0, ($length - mb_strlen($trailingChar))) . $trailingChar;

    } else {

        return $string;

    }

}

echo shortenString('This is some text to test the function with.', 20); // This is some text t…
echo shortenString('This is some text to test the function with.', 20, '...'); // This is some text t...
echo shortenString('Test.', 20); // Test.
echo shortenString('Test.', []); // Returns false
Tim Bennett is a freelance web designer from Leeds. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.