Как узнать длину строки php
Перейти к содержимому

Как узнать длину строки php

  • автор:


В отличие от strlen() , iconv_strlen() учитывает кодировку строки. Длина string не обязательно будет соответствовать количеству байт в ней, так как в различных кодировках различные символы кодируются различным количеством байт, например, юникод может быть и двух-, и четырёхбайтным.

Список параметров

Если параметр encoding опущен, предполагается, что кодировка строки string эквивалентна значению iconv.internal_encoding.

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

Возвращает количество символов в string как целое число или false в случае возникновения ошибки при кодировании.

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

Версия Описание
8.0.0 encoding теперь допускает значение null.

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

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

User Contributed Notes 2 notes

17 years ago

If iconv_strlen is passed a UTF-8 string containing badly formed sequences, it will return FALSE. This is in contrast to mb_strlen of the behaviour of utf8_decode, which strip out any bad sequences;

# UTF-8 string containing bad sequence: \xe9
$str = «I?t?rn?ti?n\xe9?liz?ti?n» ;

print «mb_strlen: » . mb_strlen ( $str , ‘UTF-8’ ). «\n» ;
print «strlen/utf8_decode: » . strlen ( utf8_decode ( $str )). «\n» ;
print «iconv_strlen: » . iconv_strlen ( $str , ‘UTF-8’ ). «\n» ;


mb_strlen: 20
strlen/utf8_decode: 20

As such it is being «stricter» than mb_strlen and it may mean you need to check for invalid sequences first. A quick way to check is to exploit the behaviour of the PCRE extension (see notes on pattern modifiers);

if ( preg_match ( ‘/^./us’ , $str , $ar ) != 1 ) die( «string contains invalid UTF-8» );

A slower but stricter check (regex) can be found at: http://www.w3.org/International/questions/qa-forms-utf-8

Similiar applies to iconv_substr, iconv_strpos and iconv_strrpos

3 years ago

Notice there is a disconnect:
>If charset`parameter is omitted, str is assumed to be encoded in iconv.internal_encoding.

But clicking on the iconv.internal_encoding link (https://www.php.net/manual/en/iconv.configuration.php), the docs indicate that iconv.internal_encoding is deprecated since 5.6.

  • Функции iconv
    • iconv_​get_​encoding
    • iconv_​mime_​decode_​headers
    • iconv_​mime_​decode
    • iconv_​mime_​encode
    • iconv_​set_​encoding
    • iconv_​strlen
    • iconv_​strpos
    • iconv_​strrpos
    • iconv_​substr
    • iconv
    • ob_​iconv_​handler
    • Copyright © 2001-2024 The PHP Group
    • My PHP.net
    • Contact
    • Other PHP.net sites
    • Privacy policy


    Строка, которую необходимо измерить. Должна быть корректная строка в кодировке UTF-8.

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

    Длина строки в случае успешного выполнения или false в случае возникновения ошибки.


    Пример #1 Пример использования grapheme_strlen()

    $char_a_ring_nfd = «a\xCC\x8A» ; // ‘LATIN SMALL LETTER A WITH RING ABOVE’ (U+00E5) normalization form «D»
    $char_o_diaeresis_nfd = «o\xCC\x88» ; // ‘LATIN SMALL LETTER O WITH DIAERESIS’ (U+00F6) normalization form «D»

    print grapheme_strlen ( ‘abc’ . $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_a_ring_nfd );

    Результат выполнения приведённого примера:


    Параметр encoding — это кодировка символов. Если он опущен или равен null , для него будет установлена внутренняя кодировка символов.

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

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


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

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

    Версия Описание
    8.0.0 Теперь параметр encoding может принимать значение null .

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

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

    User Contributed Notes 7 notes

    12 years ago

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

    16 years ago

    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.

    16 years ago

    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

    4 years ago

    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.

    15 years ago

    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.

    17 years ago

    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.

    17 years ago

    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_​pad
      • 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
      • Copyright © 2001-2024 The PHP Group
      • My PHP.net
      • Contact
      • Other PHP.net sites
      • Privacy policy

      Какая функция возвращает длину строки в php?

      Для получения длины строки в PHP используется функция strlen() .

      Возвращает длину строки string.

       $str = 'abcdefghi'; echo $strlen($str); // => 9 

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *