What potential issues could arise when using the substr function in PHP to truncate a string?

One potential issue when using the substr function in PHP to truncate a string is that it may not handle multi-byte characters correctly, leading to unexpected results or broken text. To solve this issue, you can use the mb_substr function instead, which is specifically designed to work with multi-byte character encodings like UTF-8.

// Using mb_substr to truncate a string with multi-byte character support
function truncateString($string, $length) {
    if (mb_strlen($string) > $length) {
        return mb_substr($string, 0, $length) . '...';
    } else {
        return $string;
    }
}

// Example usage
$string = "Hello, 世界!";
$truncatedString = truncateString($string, 5);
echo $truncatedString; // Output: Hello...