Truncating Text in PHP?

Truncating Text in PHP?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Truncating Text in PHP: Beyond Simple String Slicing

Truncating text is a common requirement when building responsive web applications, handling database exports, or generating previews for search results. The most naive approach involves using substr() to chop a string at a specific character index. While this works perfectly for fixed-width encodings like ASCII, it fails catastrophically with multi-byte characters such as emojis or accented letters. If you truncate "Café" after three characters, you get "Caf", but if you attempt to truncate an emoji sequence like "👨‍👩‍👧‍👦", a raw character split will result in broken glyphs and mojibake.

To handle this correctly, you need to count graphemes (visual characters) rather than bytes or code points. The standard library function mb_strcut() was introduced in PHP 8.1 specifically for this purpose. It accepts the desired length as a number of characters and handles UTF-8 multi-byte sequences internally.

Here is a practical implementation using the modern approach:

function truncateText(string $text, int $length): string {
    // Ensure we are working with the full text before cutting
    if (mb_strlen($text) <= $length) {
        return $text;
    }

    // Use mb_strcut to handle multi-byte characters correctly
    return mb_strcut($text, 0, $length, 'UTF-8') . '...';
}

// Example usage
$original = "Hello 👨‍👩‍👧‍👦 World! This is a test.";
echo truncateText($original, 20); 
// Output: "Hello 👨‍👩‍👧......"

This function preserves the integrity of complex scripts and emoji sequences. It returns the original text unchanged if the length is already within bounds, preventing unnecessary processing. The addition of an ellipsis ('...') is a standard UI convention to indicate omitted content.

For projects running on PHP versions prior to 8.1, mb_strcut is unavailable, forcing developers to rely on older workarounds. A common pattern found in community resources involves combining explode() and array_slice(). This method splits the string based on a specific delimiter, such as a space, takes the first N words, and rejoins them.

function truncateWords(string $text, int $wordCount): string {
    if (preg_match('/\s/', $text) === false || strlen($text) <= ($wordCount * 5)) {
        // Fallback or early exit logic depending on needs
        return $text;
    }

    $words = explode(' ', $text, $wordCount + 1);
    return implode(' ', array_slice($words, 0, -1));
}

While the word-counting method is intuitive, it introduces significant fragility. It assumes that spaces separate logical words, which breaks down with hyphenated compounds, URLs, or code snippets. More critically, it does not respect character boundaries; truncating a sentence in the middle of a word often looks unprofessional and can obscure meaning.

The primary trade-off when choosing a truncation strategy lies between precision and performance. Multi-byte handling functions like mb_strcut are slightly more computationally expensive than raw string operations because they must decode and analyze byte sequences to identify grapheme clusters. However, for display purposes where visual correctness is paramount, this overhead is negligible compared to the cost of rendering broken text or implementing complex regex-based fallbacks.

In a Laravel context, you might encapsulate this logic within a service provider or a custom helper function to keep your views clean. If you are dealing with very large datasets in memory, consider processing truncation at the database level using prepared statements if the column supports specific truncation functions, though most SQL engines truncate by bytes rather than graphemes, requiring application-side handling for visual accuracy.

When integrating third-party libraries or checking external resources for legacy solutions, always verify version compatibility. The link to The Odin Project's tutorial on this topic serves as a good reference for understanding the historical context of these problems, but relying on mb_substr tricks from 2015 is no longer necessary in modern PHP stacks.

Our network