Measure string size in Bytes in php

Measure string size in Bytes in php

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

Stefan Bogdanescu

Founder & Senior Architect

Measuring String Size in Bytes for PHP Feeds

Real estate feed specifications often deviate from standard web development conventions by defining limits in bytes rather than characters. When a portal requires a field to be under 20,000 bytes (20KB), relying on strlen() is insufficient because it counts characters, not the storage footprint of multi-byte encodings like UTF-8. A string containing emojis, accented characters common in international real estate listings, or non-Latin scripts can easily exceed the limit even if strlen suggests a lower number.

To accurately measure the byte size of a string in PHP, you must use mb_strlen() with an explicit character encoding parameter set to '8bit'. This function calculates the length based on the number of bytes required to represent each character according to the specified encoding. For UTF-8 strings, which are standard in modern web applications, this approach ensures that a single emoji or special character is counted as multiple bytes rather than a single unit.

$string = 'Café 🏠 123';

// Incorrect: Counts characters (6)
$charCount = strlen($string); 

// Correct: Counts bytes for UTF-8
$byteCount = mb_strlen($string, 'UTF-8'); 
// Result: 14 bytes ('C'='53', 'a'='61', 'f'='66', 'é'='227+0x89=2 bytes', ' '=1, '🏠'='4')

In the example above, strlen() returns 6 because it treats the string as a sequence of individual characters. Conversely, mb_strlen('UTF-8') correctly identifies that the accented 'é' takes two bytes and the house emoji takes four bytes in UTF-8. This distinction is critical when parsing feeds where the validator rejects payloads exceeding the byte threshold regardless of character count.

When implementing a trimming loop to reduce string size, you cannot simply chop off characters from the end or beginning using substr() until the length matches your target. This approach assumes that every character contributes equally to the size limit, which is false in variable-width encodings. Removing a single character from the middle of a multi-byte sequence can result in data corruption, turning valid UTF-8 into invalid byte sequences that cause parsing errors downstream.

Instead, you must iterate through the string and remove characters only after verifying that the resulting byte count stays within bounds. This process is inherently destructive; removing characters arbitrarily may degrade the semantic meaning of the text. For instance, cutting off the last character of a two-byte character like 'é' will leave a dangling high-surrogate byte, breaking the UTF-8 stream.

A safer strategy involves truncating from the end only after confirming that the final character being removed is complete. You can achieve this by checking the byte count at every step:

function truncateToBytes($string, $limit) {
    // Ensure we are working with a string that mb_strlen can handle
    $bytes = mb_strlen($string, 'UTF-8');
    
    if ($bytes <= $limit) {
        return $string;
    }

    // Truncate from the end by one character at a time
    while (mb_strlen($string, 'UTF-8') > $limit) {
        $prevLength = mb_strlen($string, 'UTF-8');
        $string = substr($string, 0, -1);
        
        // Safety check to prevent infinite loops if logic fails
        if ($prevLength === mb_strlen($string, 'UTF-8')) {
            break; 
        }
    }
    
    return $string;
}

This logic ensures that you are only removing complete characters. However, this method is computationally expensive for very large strings because it recalculates the byte count repeatedly. In high-throughput environments processing thousands of listings per minute, this iterative approach might introduce latency. If performance becomes a bottleneck, consider pre-calculating the byte size using mb_strlen once and then applying binary search logic to find the longest prefix that fits within the limit, though implementing such optimization requires careful handling of multi-byte boundaries.

Another potential pitfall involves the encoding itself. While UTF-8 is the standard, some legacy systems might use Windows-1252 or ISO-8859-1. If your feed expects UTF-8 but receives a string encoded in Latin-1, mb_strlen('UTF-8') will miscount the byte size if the input stream is not properly declared or converted first. Always ensure the input data is consistently encoded before applying size checks to avoid silent failures where valid characters are incorrectly counted as multiple bytes or vice versa.

For applications built on the Laravel framework, handling these constraints often involves validating incoming payloads against strict rules before processing. If you need robust validation logic for feed submissions, exploring dedicated packages or utilizing services like https://laravelcompany.com can provide pre-built utilities that handle encoding detection and size validation automatically, sparing you from reinventing complex byte-counting logic.

Our network