#development #laravel #php

Imagine you need to check if a string is smaller than a given byte size. For example, you need to check if a string is smaller than 100 bytes.

You can use the strlen function to check the string size in bytes. The strlen function returns the number of bytes and not the number of characters. So, if you have a string with 100 characters, it will return 100, but if you have a string with 100 characters and 100 emojis, it will return 400.

If you want to count the number of characters, counting multi-byte characters (such as emoji's) as single characters, you need to use the mb_strlen function instead.

An example:

1// Hello in Arabic
2$utf8 = "السلام علیکم ورحمة الله وبرکاته!";
3
4strlen($utf8) // 59
5mb_strlen($utf8, 'utf8') // 32

If you happen to use the Str::length() method in Laravel, be aware that it uses the mb_strlen function under the hood.

 1/**
 2 * Return the length of the given string.
 3 *
 4 * @param  string  $value
 5 * @param  string|null  $encoding
 6 * @return int
 7 */
 8public static function length($value, $encoding = null)
 9{
10    return mb_strlen($value, $encoding);
11}

The same applies to for example the Str::limit method in Laravel:

 1/**
 2 * Limit the number of characters in a string.
 3 *
 4 * @param  string  $value
 5 * @param  int  $limit
 6 * @param  string  $end
 7 * @return string
 8 */
 9public static function limit($value, $limit = 100, $end = '...')
10{
11    if (mb_strwidth($value, 'UTF-8') <= $limit) {
12        return $value;
13    }
14
15    return rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8')).$end;
16}

So, if you want to truncate a string to a maximum byte size using PHP, I ended up with the following method:

 1function truncateToMaxSize(string $inputString, int $maxSizeInMB, string $encoding = 'UTF-8') : string {
 2    $maxSizeInBytes = $maxSizeInMB * 1024 * 1024; // Convert MB to bytes
 3
 4    if (strlen($inputString) <= $maxSizeInBytes) {
 5        return $inputString; // No need to truncate
 6    }
 7
 8    $truncatedString = substr($inputString, 0, $maxSizeInBytes);
 9
10    // To ensure that you don't cut off a multi-byte character at the end
11    $truncatedString = mb_substr(
12        $truncatedString,
13        0,
14        mb_strlen($truncatedString, $encoding),
15        $encoding,
16    );
17
18    return $truncatedString;
19}