Skip to content
PHP Logo

What potential pitfalls should I be aware of when implementing a text truncation feature in PHP?

One potential pitfall when implementing a text truncation feature in PHP is not taking into account multibyte characters, which can result in truncated text appearing incorrectly. To solve this issue, you can use the mb_substr function instead of substr to handle multibyte characters properly.

php
// Function to truncate a string with multibyte character support
function truncate_text($text, $length) {
    if(mb_strlen($text) > $length) {
        return mb_substr($text, 0, $length) . '...';
    } else {
        return $text;
    }
}

// Example usage
$text = "This is a sample text with multibyte characters: こんにちは";
$truncated_text = truncate_text($text, 10);
echo $truncated_text; // Output: This is a...