Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measure string size in Bytes in php

I am doing a real estate feed for a portal and it is telling me the max length of a string should be 20,000 bytes (20kb), but I have never run across this before.

How can I measure byte size of a varchar string. So I can then do a while loop to trim it down.

like image 419
Liam Bailey Avatar asked Sep 27 '11 12:09

Liam Bailey


People also ask

How to get the size of a string PHP?

You can simply use the PHP strlen() function to get the length of a string. The strlen() function return the length of the string on success, and 0 if the string is empty.

Which function returns the number of bytes of a string?

OCTET_LENGTH returns the number of bytes in a character column, quoted string, host variable, or SPL variable.

What is Mb_strlen?

In PHP, multibyte string length (mb_strlen) function is used to get the total string length of a specified string. This function is supported in PHP 4.6.

Is substring in string PHP?

You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false .


1 Answers

You can use mb_strlen() to get the byte length using a encoding that only have byte-characters, without worring about multibyte or singlebyte strings. For example, as drake127 saids in a comment of mb_strlen, you can use '8bit' encoding:

<?php     $string = 'Cién cañones por banda';     echo mb_strlen($string, '8bit'); ?> 

You can have problems using strlen function since php have an option to overload strlen to actually call mb_strlen. See more info about it in http://php.net/manual/en/mbstring.overload.php

For trim the string by byte length without split in middle of a multibyte character you can use:

mb_strcut(string $str, int $start [, int $length [, string $encoding ]] ) 
like image 51
PhoneixS Avatar answered Sep 22 '22 02:09

PhoneixS