What are the potential pitfalls of using substr() in PHP to limit the length of a string for display in HTML?

Using substr() to limit the length of a string for display in HTML can potentially cut off the string in the middle of a word, causing readability issues. To solve this problem, we can use the mb_substr() function instead, which handles multi-byte characters properly and ensures that the string is cut off at a valid point.

<?php
$string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$maxLength = 20;

if(mb_strlen($string) > $maxLength){
    $trimmedString = mb_substr($string, 0, $maxLength) . "...";
} else {
    $trimmedString = $string;
}

echo $trimmedString;
?>