Php длина строки байт

mb_strlen

Параметр encoding представляет собой символьную кодировку. Если он опущен или равен null , вместо него будет использовано значение внутренней кодировки.

Возвращаемые значения

Возвращает количество символов в строке ( string ) string , имеющих кодировку символов encoding . Многобайтовый символ вычисляется как 1.

Ошибки

Если кодировка неизвестна, генерируется ошибка уровня E_WARNING .

Список изменений

Смотрите также

  • mb_internal_encoding() — Установка/получение внутренней кодировки скрипта
  • grapheme_strlen() — Получает длину строки в единицах графемы
  • iconv_strlen() — Возвращает количество символов в строке
  • strlen() — Возвращает длину строки

User Contributed Notes 7 notes

If you are unsure about what $encoding can be set to, here’s a full list of all the encodings supported by this extension:

Speed of mb_strlen varies a lot according to specified character set.

If you need length of string in bytes (strlen cannot be trusted anymore because of mbstring.func_overload) you should use .
It’s the fastest way (still a way slower than strlen, though) to determine byte length of string. Other single byte character sets (ASCII, ISO-8859-1, . ) are several times slower than 8bit.

Just did a little benchmarking (1.000.000 times with lorem ipsum text) on the mbs functions

especially mb_strtolower and mb_strtoupper are really slow (up to 100 times slower compared to normal functions). Other functions are alike-ish, but sometimes up to 5 times slower.

just be cautious when using mb_ functions in high frequented scripts.

# test runs: 1000000
# benchmarking strlen vs. mb_strlen
# normal strlen: 3.6795361042023 ms, average: 3.6795361042023E-6 ms
# mb_strlen: 5.5934538841248 ms, average: 5.5934538841248E-6 ms
ok 1 — mb_strlen is slower than strlen
# mb_strlen is 1.52 slower than strlen
#
#
# benchmarking strpos vs. mb_strpos
# normal strpos: 5.5523281097412 ms, average: 5.5523281097412E-6 ms
# mb_strlen: 31.180974960327 ms, average: 3.1180974960327E-5 ms
ok 2 — mb_strlen is slower than strlen
# mb_strpos is 5.62 slower than strpos
#
#
# benchmarking substr vs. mb_substr
# normal substr: 3.4437320232391 ms, average: 3.4437320232391E-6 ms
# mb_strlen: 3.5374181270599 ms, average: 3.5374181270599E-6 ms
ok 3 — mb_strlen is slower than strlen
# mb_substr is 1.03 slower than substr
#
#
# benchmarking strtolower vs. mb_strtolower
# normal strtolower: 4.446839094162 ms, average: 4.446839094162E-6 ms
# mb_strlen: 193.44901108742 ms, average: 0.00019344901108742 ms
ok 4 — mb_strlen is slower than strlen
# mb_strtolower is 43.5 slower than strtolower
#
#
# benchmarking strtoupper vs. mb_strtoupper
# normal strtoupper: 3.0210740566254 ms, average: 3.0210740566254E-6 ms
# mb_strlen: 340.71775603294 ms, average: 0.00034071775603294 ms
ok 5 — mb_strlen is slower than strlen
# mb_strtoupper is 112.78 slower than strtoupper

Читайте также:  Php программисты в сша

It may not be clear whether PHP actually supports utf-8, which is the current de facto standard character encoding for Web documents, which supports most human languages. The good news is: it does.

I wrote a test program which successfully reads in a utf-8 file (without BOM) and manipulates the characters using mb_substr, mb_strlen, and mb_strpos (mb_substr should normally be avoided, as it must always start its search at character position 0).

The results with a variety of Unicode test characters in utf-8 encoding, up to four bytes in length, were mostly correct, except that accent marks were always mistakenly treated as separate characters instead of being combined with the previous character; this problem can be worked around by programming, when necessary.

If you find yourself without the mb string functions and can’t easily change it, a quick hack replacement for mb_strlen for utf8 characters is to use a a PCRE regex with utf8 turned on.

This is basically an ugly hack which counts all single character matches, and I’d expect it to be painfully slow on large strings.

Thank you Peter Albertsson for presenting that!

After spending more than eight hours tracking down two specific bugs in my mbstring-func_overloaded environment I have learned a very important lesson:

Many developers rely on strlen to give the amount of bytes in a string. While mb-overloading has very many advantages, the most hard-spotted pitfall must be this issue.

Two examples (from the two bugs found earlier):

1. Writing a string to a file:

$str = «string with utf-8 chars åèä — doo-bee doo-bee dooh» ;
$fp = fopen ( $this -> _file , «wb» );
if ( $fp ) $len = strlen ( $str );
fwrite ( $fp , $str , $len );
>
?>

PS This is found i the PEAR::Cache_Lite package (Lite.php) — Reported

2. Iterating through a string’s characters:

$str = «string with utf-8 chars åèö — doo-bee doo-bee dooh» ;
$newStr = «» ;
for ( $i = 0 ; $i < strlen ( $str ); $i ++) $newStr .= $str [ $i ];
>
?>

Both of these situations will fail to save / store the last characters in $str. This can be very hard to spot and can be especially fatal for say serialized strings, xml etc.

So, try to avoid these situations to support overloaded environments, and remeber Peter Albertssons remark if you find problems under such an environment.

I have been working with some funny html characters lately and due to the nightmare in manipulating them between mysql and php, I got the database column set to utf8, then store characters with html enity «ọ» as ọ in the database and set the encoding on php as «utf8».

Читайте также:  Цвета в питоне через

This is where mb_strlen became more useful than strlen. While strlen(‘ọ’) gives result as 3, mb_strlen(‘ọ’,’UTF-8′) gives 1 as expected.

But left(column1,1) in mysql still gives wrong char for a multibyte string. In the example above, I had to do left(column1,3) to get the correct string from mysql. I am now about to investigate multibyte manipulation in mysql.

  • Функции для работы с многобайтовыми строками
    • mb_​check_​encoding
    • mb_​chr
    • mb_​convert_​case
    • mb_​convert_​encoding
    • mb_​convert_​kana
    • mb_​convert_​variables
    • mb_​decode_​mimeheader
    • mb_​decode_​numericentity
    • mb_​detect_​encoding
    • mb_​detect_​order
    • mb_​encode_​mimeheader
    • mb_​encode_​numericentity
    • mb_​encoding_​aliases
    • mb_​ereg_​match
    • mb_​ereg_​replace_​callback
    • mb_​ereg_​replace
    • mb_​ereg_​search_​getpos
    • mb_​ereg_​search_​getregs
    • mb_​ereg_​search_​init
    • mb_​ereg_​search_​pos
    • mb_​ereg_​search_​regs
    • mb_​ereg_​search_​setpos
    • mb_​ereg_​search
    • mb_​ereg
    • mb_​eregi_​replace
    • mb_​eregi
    • mb_​get_​info
    • mb_​http_​input
    • mb_​http_​output
    • mb_​internal_​encoding
    • mb_​language
    • mb_​list_​encodings
    • mb_​ord
    • mb_​output_​handler
    • mb_​parse_​str
    • mb_​preferred_​mime_​name
    • mb_​regex_​encoding
    • mb_​regex_​set_​options
    • mb_​scrub
    • mb_​send_​mail
    • mb_​split
    • mb_​str_​split
    • mb_​strcut
    • mb_​strimwidth
    • mb_​stripos
    • mb_​stristr
    • mb_​strlen
    • mb_​strpos
    • mb_​strrchr
    • mb_​strrichr
    • mb_​strripos
    • mb_​strrpos
    • mb_​strstr
    • mb_​strtolower
    • mb_​strtoupper
    • mb_​strwidth
    • mb_​substitute_​character
    • mb_​substr_​count
    • mb_​substr

    Источник

    Длина строки и массива в PHP

    Узнать длину строки и массива в PHP

    Привет. В PHP довольно часто приходится работать со строками и массивами и почти во всех случаях требуется узнать их длину (length). Вполне типичная ситуация и для нее есть встроенные функции в PHP. Но есть некоторые нюансы, к примеру то, что одна из функций, которая показывает длину строки — srtlen считает не количество символов в тексте, а количество байт, который занимает каждый символ. Если латинский символ занимает 1 байт, то на кириллице он займет 2 байта. Об этом я же упоминал в статье по теме: как обрезать текст по количеству слов и символов. Но сейчас постараемся рассмотреть некоторые примеры более детально.

    Телеграм-канал serblog.ru

    Узнать длину строки в PHP

    Первая функция, которая будет вычислять длину строки в PHP, будет strlen.

    $str = "Hello World"; echo strlen($str); // 11 символов вместе с пробелом

    $str = «Hello World»; echo strlen($str); // 11 символов вместе с пробелом

    А если мы напишем примерно то же самое, но на русском, то получим такой вариант:

    $str = "Привет Мир"; echo strlen($str); // 19 символов вместе с пробелом

    $str = «Привет Мир»; echo strlen($str); // 19 символов вместе с пробелом

    В этом случае, как я уже говорил ранее, каждый символ займет 2 байта + 1 байт — это пробел. В итоге мы получим не совсем то, что ожидали. Поэтому в случае с кириллицей, чтобы определить длину строки, следует использовать другие функции. Первая — mb_strlen

    $str = "Привет Мир"; echo mb_strlen($str); // 10 символов вместе с пробелом

    $str = «Привет Мир»; echo mb_strlen($str); // 10 символов вместе с пробелом

    В этом случае подсчет символов в строки будет одинаковым как на английском, так и на русском языках. Даже если символ занимает несколько байт, то будет посчитан, как один. Так же есть еще одна функция, чтобы узнать длину строки в символах — iconv_strlen

    $str = "Привет Мир"; echo iconv_strlen($str); // 10 символов вместе с пробелом

    $str = «Привет Мир»; echo iconv_strlen($str); // 10 символов вместе с пробелом

    iconv_strlen учитывает кодировку строки, ее можно указать вторым параметром. Если она не указана, то кодировка будет внутренней. То есть самого файла.

    echo iconv_strlen($str, "UTF-8");

    echo iconv_strlen($str, «UTF-8»);

    Если возникла необходимость проверить длину строки без пробелов, то потребуется дополнительная функция str_replace

    $str = "Привет Мир"; echo iconv_strlen(str_replace(' ', '', $str)); // 9 символов без пробелов //iconv_strlen или mb_strlen

    $str = «Привет Мир»; echo iconv_strlen(str_replace(‘ ‘, », $str)); // 9 символов без пробелов //iconv_strlen или mb_strlen

    Узнать длину массива в PHP

    функция, которая позволяет узнать длину массива в PHP — count.

    $arr = ["Иван", "Марина", "Сергей", "Алина"]; echo 'Длина массива ' . count($arr) . ' элемента'; // Длина массива: 4 элемента

    $arr = [«Иван», «Марина», «Сергей», «Алина»]; echo ‘Длина массива ‘ . count($arr) . ‘ элемента’; // Длина массива: 4 элемента

    То же самое будет с массивом, где есть ключи и значения.

    $arr = ['name' => "Иван", "city" => "NY", "age" => 34]; echo 'Длина массива ' . count($arr) . ' элемента'; // Длина массива: 3 элемента

    $arr = [‘name’ => «Иван», «city» => «NY», «age» => 34]; echo ‘Длина массива ‘ . count($arr) . ‘ элемента’; // Длина массива: 3 элемента

    strlen() Подсчет количества байт в строке
    mb_stren() Подсчет символов в строке
    iconv_strlen() Подсчет символов строки с учетом кодировки
    count() Подсчет элементов массива

    На этом можно завершить. Теперь вы можете самостоятельно узнать длину строки в PHP и определить длину массива. А если возникнут вопросы, задавайте их в комментариях.

    Источник

    PHP strlen() Function

    The strlen() function returns the length of a string.

    Syntax

    Parameter Values

    Technical Details

    Return Value: Returns the length of a string (in bytes) on success, and 0 if the string is empty
    PHP Version: 4+

    More Examples

    Example

    Return the length of the string «Hello World»:

    Unlock Full Access 50% off

    COLOR PICKER

    colorpicker

    Join our Bootcamp!

    Report Error

    If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

    Thank You For Helping Us!

    Your message has been sent to W3Schools.

    Top Tutorials
    Top References
    Top Examples
    Get Certified

    W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

    Источник

Оцените статью