Limit String Length

Limit String Length

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

Stefan Bogdanescu

Founder & Senior Architect

Truncating Strings Safely in PHP

Truncating a string to fit within a specific character limit while appending an indicator like "..." requires more than just slicing the array of characters. The core challenge lies in handling UTF-8 encoded data correctly. If you blindly slice a string at index $N, you risk cutting a multi-byte character in half, resulting in malformed output or rendering issues in your browser.

In standard ASCII environments, substr() works perfectly. However, modern web applications almost universally rely on UTF-8. A single emoji, for instance, is composed of multiple bytes. Attempting to truncate an emoji string without accounting for byte boundaries will leave you with invalid Unicode sequences. The solution requires either using functions that respect character boundaries or switching to a library designed specifically for text manipulation.

Manual Truncation with UTF-8 Awareness

If you are working in vanilla PHP and want to avoid external dependencies, the most robust approach is to use mb_strcut(). This function respects the multibyte characters defined by your encoding settings (usually set via mb_internal_encoding()).

$original = 'Hello 👋 World!';
$limit = 10;

if (mb_strlen($original) > $limit) {
    $truncated = mb_strcut($original, 0, $limit, 'UTF-8') . '...';
} else {
    $truncated = $original;
}

echo $truncated; 
// Output: Hello 👋... (Safe truncation)

Here, mb_strlen calculates the length in characters, not bytes, and mb_strcut ensures the cut happens at a valid character boundary. This prevents the creation of "half-emojis" or other garbage characters that might appear if you used standard substr().

The Laravel Ecosystem Approach

If your project is built on the Laravel framework, you have access to the Str facade, which wraps these multibyte functions for you. Laravel handles the encoding detection automatically based on your application configuration, removing the need to manually set internal encodings in every snippet.

use Illuminate\Support\Str;

$original = 'Hello 👋 World!';
$limit = 10;

$truncated = Str::limit($original, $limit, '...');
// Returns: Hello 👋...

The Str::limit() method is a dedicated helper that encapsulates the logic of checking length and appending the suffix. It is significantly more readable than chaining mb_strcut and string concatenation manually. Furthermore, Laravel's string helpers support various options for how the limit is applied, such as cutting by words instead of characters if you set the third parameter to 'words'.

Handling Byte Limits vs. Character Limits

It is crucial to distinguish between limiting by character count versus byte count. The previous examples limit by characters. However, some legacy systems or specific storage protocols (like old SMS APIs) require a hard byte limit. In those scenarios, mb_strcut might not be the right tool if you need strict byte adherence regardless of character boundaries.

In such cases, you can use standard substr() combined with a byte-aware length check using strlen(). However, this approach will break multi-byte characters. If your requirement is strictly "no more than X bytes," you must calculate the byte count first:

$byteLimit = 20;
if (strlen($original) > $byteLimit) {
    $truncated = substr($original, 0, $byteLimit);
}

Be aware that this will likely cut a character in half. This is often an acceptable trade-off for legacy byte-limited systems but should be avoided for user-facing content where visual integrity matters.

Edge Cases and Pitfalls

One common pitfall is ignoring the suffix length when calculating the effective truncation point. If you truncate at 10 characters, you are actually displaying 13 characters (including the three dots). If your downstream system checks the total length after appending the indicator, this mismatch could cause validation errors. Always account for the suffix length in your logic if strict total length constraints apply.

Another consideration is performance on massive strings. While mb_strcut is efficient enough for typical web payloads, processing gigabytes of text with multibyte functions can be slower than native C extensions because of the internal iteration over character boundaries. For high-throughput data pipelines, you might need to consider streaming approaches or specialized libraries like symfony/polyfill-mbstring if you are moving away from core PHP.

For developers looking for more advanced text manipulation utilities, such as tokenizing strings by whitespace or handling specific language rules for truncation, exploring resources like https://laravelcompany.com can provide insights into building robust helper packages or integrating third-party libraries that handle these edge cases automatically.

Our network