Making sure PHP substr finishes on a word not a character

Making sure PHP substr finishes on a word not a character

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

Stefan Bogdanescu

Founder & Senior Architect

Making sure PHP substr finishes on a word, not a character

Using substr() to truncate text is a common pattern, but it often produces ugly output when you simply need to stop exactly at a specific character count. If you run substr($body, 0, 260) on a string like "Hello world this is a test", the result might cut in the middle of a word if the 260th character falls inside it. You end up with fragments like "...test." becoming "...testi". This is rarely what you want for user-facing content, especially when generating previews or summaries.

To solve this, you need to trim the substring from the end until the last full word is reached. The core logic involves calculating how many characters to remove based on the position of the final complete word relative to your truncation limit. This approach ensures that every truncated string ends cleanly with a whitespace character preceding the cut-off point.

The Logic Behind Clean Truncation

The most straightforward method relies on finding the last space character within the desired substring length. If you extract the first 260 characters and then search backwards for the position of the final space, you can calculate exactly how many characters need to be removed to reach that space.

Here is a practical implementation using native PHP functions:

function truncateAtWord($string, $length) {
    if (mb_strlen($string) <= $length) {
        return $string;
    }

    // Extract the raw substring up to the limit
    $sub = substr($string, 0, $length);

    // Find the position of the last space within that substring
    $lastSpacePos = strrpos($sub, ' ');

    if ($lastSpacePos !== false) {
        // Remove everything after the last space
        return substr($sub, 0, $lastSpacePos);
    }

    // Fallback: If no space is found (e.g., a single long word), truncate anyway
    return substr($string, 0, $length);
}

This function first checks if the string is already short enough to avoid unnecessary processing. It then extracts the substring and uses strrpos() to locate the rightmost space character. By slicing the string up to that index, you guarantee that the result ends with a complete word followed by whitespace (or the very last character if no space exists).

Handling Multibyte Characters

If your content is not strictly ASCII—meaning it contains UTF-8 characters like accented letters or emojis—you must be careful. Using strlen() and substr() directly on UTF-8 strings can split a multi-byte character, resulting in mojibake (garbled text). In such cases, switching to mb_substr is essential.

The logic remains the same, but you must adjust the functions used: use mb_strlen for length checks, mb_substr for slicing, and mb_strrpos for finding positions. Ensure that the internal encoding of your string matches the one passed to these functions, typically UTF-8.

function truncateAtWordUTF8($string, $length) {
    if (mb_strlen($string, 'UTF-8') <= $length) {
        return $string;
    }

    $sub = mb_substr($string, 0, $length, 'UTF-8');
    $lastSpacePos = mb_strrpos($sub, ' ', 'UTF-8');

    if ($lastSpacePos !== false) {
        return mb_substr($sub, 0, $lastSpacePos, 'UTF-8');
    }

    return mb_substr($string, 0, $length, 'UTF-8');
}

Alternative Approaches and Trade-offs

While manual string manipulation works well for most scenarios, it adds complexity. If you are already using a framework like Laravel, consider leveraging built-in helpers that handle these edge cases more gracefully. The Str facade provides methods like limit(), which accepts an additional parameter to specify the number of words rather than characters. This abstracts away the truncation logic entirely:

use Illuminate\Support\Str;

$text = Str::limit($body, 260); 
// Note: Str::limit defaults to character count, so you may still need custom logic 
// unless you switch to word-based limits using Str::words().

In many cases, switching to Str::words() with a specific word count is cleaner than character-based truncation. This ensures the output respects language boundaries naturally without manual space-finding logic.

Why Not Use Regex?

You might wonder if a regular expression could solve this more elegantly. While patterns like .*\s can match content up to the last space, they often require lookahead assertions or complex grouping to enforce strict length limits before matching. For simple truncation tasks, regex introduces unnecessary overhead and reduces readability compared to straightforward string functions. Stick with substr combined with strrpos (or their multibyte equivalents) for clarity and performance unless you have specific formatting requirements that demand pattern matching.

Our network