Get first 100 characters from string, respecting full words

Get first 100 characters from string, respecting full words

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

Stefan Bogdanescu

Founder & Senior Architect

Get first 100 characters from string, respecting full words

Truncating text to a fixed length is a common requirement in web development, but doing so blindly often results in broken sentences and incomplete words. A naive approach using substr($string, 0, 100) guarantees the length constraint is met, but it frequently cuts off mid-word, creating artifacts like "This is a sentenc" or "data-bas". While valid in some contexts, this rarely aligns with user expectations for readability.

To achieve a truncation that respects word boundaries, you must shift from character-based logic to token-based iteration. The core strategy involves iterating through the string word by word, accumulating them into a buffer until adding the next word would exceed the 100-character limit. Once the limit is threatened, you discard the current candidate word and finalize the output.

Implementing Word-Aware Truncation in PHP

In standard PHP, there isn't a single built-in function that performs this logic out of the box because it requires maintaining state about the accumulated length versus the target length. You have to write a small loop to handle the accumulation.

The most robust method involves splitting the string into an array of words and reconstructing them. However, simple explode(' ', $text) is risky because it breaks on multiple spaces, tabs, or newlines, potentially losing formatting information. Instead, use preg_split() with a regex pattern that matches any whitespace character sequence.

Here is a practical implementation:

function truncateRespectingWords($text, $limit) {
    // Split the text by any sequence of whitespace to handle spaces, tabs, newlines cleanly
    $words = preg_split('/\s+/', $text);

    $result = '';
    $currentLength = 0;

    foreach ($words as $word) {
        if (strlen($word) + $currentLength + strlen(' ') <= $limit) {
            // If adding the word and a space stays within limit, add it
            $result .= $word . ' ';
            $currentLength = strlen($result);
        } else {
            // If adding this word exceeds the limit, stop here
            break;
        }
    }

    // Trim trailing whitespace to ensure we don't return a string ending in a space
    return trim($result);
}

In this loop, $currentLength tracks the exact byte count of the constructed string. Before appending a new word, the code checks if length(word) + current_length + 1 (for the space) fits within $limit. If it does, the word is appended. If not, the loop breaks immediately, preserving the last valid partial sentence.

Handling Edge Cases and Encoding

When implementing this logic, encoding matters significantly. The strlen() function in PHP counts bytes, not characters. In UTF-8 environments, many characters (like accented letters or emojis) take up multiple bytes. If your text contains such characters, a 100-byte limit might appear shorter visually than intended, or conversely, you might cut off a word after fewer visible characters than expected.

For strict character counting in multi-byte encodings, mb_strlen() and mb_substr() are preferred. However, using them inside a loop with regex splitting can get messy if the delimiter also needs to be handled as bytes/chars consistently. If your application strictly requires byte-level precision for legacy reasons, stick to strlen. If you prioritize visual length for modern web content, consider switching to:

function truncateRespectingWordsMB($text, $limit) {
    $words = preg_split('/\s+/', $text);
    $result = '';
    $currentLength = 0;

    foreach ($words as $word) {
        if (mb_strlen($word) + mb_strlen(trim($result)) + 1 <= $limit) {
            $result .= $word . ' ';
            $currentLength = mb_strlen(trim($result));
        } else {
            break;
        }
    }
    
    return trim($result);
}

This version uses mb_strlen to ensure the visual character count is respected, which is generally safer for internationalization (i18n) purposes.

Trade-offs and Performance Considerations

The primary trade-off here is performance versus readability. A simple substr() operation is O(1) or O(n) depending on implementation details but runs in nanoseconds. The word-aware loop iterates through every word, recalculating lengths, making it slower for massive text blocks. However, for typical UI labels, email subjects, or meta descriptions—where truncation is used—the performance overhead is negligible compared to database I/O or rendering.

Another pitfall is handling empty strings or strings with only whitespace. The regex split handles whitespace-only strings gracefully by returning an empty array or a single empty string, preventing infinite loops or errors in the loop logic. Always validate that $limit is greater than zero before calling these functions to avoid unexpected behavior.

If you are building this on top of a Laravel application, you might consider wrapping this logic in a trait or a helper class within your App\Utils namespace. For more complex truncation needs involving HTML entities or Markdown links, simple string splitting will break the document structure. In those specific scenarios, using libraries like parsedown or dedicated text sanitization packages becomes necessary to ensure safety and integrity.

Our network