What are some potential pitfalls when truncating strings in PHP and how can they be avoided?
One potential pitfall when truncating strings in PHP is not taking into account multi-byte characters, which can result in corrupted text. To avoid this issue, you can use the `mb_substr()` function instead of `substr()` to ensure proper handling of multi-byte characters.
// Truncate a string with proper handling of multi-byte characters
function truncateString($string, $length) {
if (mb_strlen($string) > $length) {
return mb_substr($string, 0, $length) . '...';
}
return $string;
}
// Example usage
$string = "Hello, 世界";
$truncatedString = truncateString($string, 5);
echo $truncatedString; // Output: Hello...