php get string length
mb_strlen
(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)
mb_strlen — Получает длину строки
Описание
Получает длину строки ( string ).
Список параметров
Строка ( string ), для которой измеряется длина.
Возвращаемые значения
Ошибки
Список изменений
Смотрите также
User Contributed Notes 7 notes
Speed of mb_strlen varies a lot according to specified character set.
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.
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.
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.
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:
2. Iterating through a string’s characters:
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.
Длина строки и массива в PHP
Привет. В PHP довольно часто приходится работать со строками и массивами и почти во всех случаях требуется узнать их длину (length). Вполне типичная ситуация и для нее есть встроенные функции в PHP. Но есть некоторые нюансы, к примеру то, что одна из функций, которая показывает длину строки — srtlen считает не количество символов в тексте, а количество байт, который занимает каждый символ. Если латинский символ занимает 1 байт, то на кириллице он займет 2 байта. Об этом я же упоминал в статье по теме: как обрезать текст по количеству слов и символов. Но сейчас постараемся рассмотреть некоторые примеры более детально.
Узнать длину строки в PHP
Первая функция, которая будет вычислять длину строки в PHP, будет strlen.
$str = «Hello World»; echo strlen($str); // 11 символов вместе с пробелом
А если мы напишем примерно то же самое, но на русском, то получим такой вариант:
$str = «Привет Мир»; echo strlen($str); // 19 символов вместе с пробелом
В этом случае, как я уже говорил ранее, каждый символ займет 2 байта + 1 байт — это пробел. В итоге мы получим не совсем то, что ожидали. Поэтому в случае с кириллицей, чтобы определить длину строки, следует использовать другие функции. Первая — mb_strlen
$str = «Привет Мир»; echo mb_strlen($str); // 10 символов вместе с пробелом
В этом случае подсчет символов в строки будет одинаковым как на английском, так и на русском языках. Даже если символ занимает несколько байт, то будет посчитан, как один. Так же есть еще одна функция, чтобы узнать длину строки в символах — iconv_strlen
$str = «Привет Мир»; echo iconv_strlen($str); // 10 символов вместе с пробелом
iconv_strlen учитывает кодировку строки, ее можно указать вторым параметром. Если она не указана, то кодировка будет внутренней. То есть самого файла.
echo iconv_strlen($str, «UTF-8»);
Если возникла необходимость проверить длину строки без пробелов, то потребуется дополнительная функция str_replace
Узнать длину массива в PHP
функция, которая позволяет узнать длину массива в PHP — count.
То же самое будет с массивом, где есть ключи и значения.
strlen() | Подсчет количества байт в строке |
mb_stren() | Подсчет символов в строке |
iconv_strlen() | Подсчет символов строки с учетом кодировки |
count() | Подсчет элементов массива |
На этом можно завершить. Теперь вы можете самостоятельно узнать длину строки в PHP и определить длину массива. А если возникнут вопросы, задавайте их в комментариях.
Как найти длину строки в PHP?
В этой статье мы рассмотрим, как в PHP вычисляется длина строки. Поговорим про известную функцию strlen и расскажем про нюансы её работы.
Итак, начнём с того, что заключим нужный текст в переменную — это позволит нам в последующем удобнее обращаться к нашей текстовой информации. К примеру:
Будем считать, что строка у нас есть, поэтому осталось определить её длину. Сделать это можно, используя всем известную функцию strlen. Единственным и обязательным параметром данной функции является строка, число символов в которой мы считаем:
Функция работает предельно просто: принимает строку и возвращает в качестве результата определённое значение, которое, кстати, вы потом сможете применять в своих скриптах и функциях. При этом удобнее будет сделать так:
Но это в том случае, если мы уже создали данную переменную, иначе можно записать код следующим образом:
То есть ничего сложного, как видите, нет. Если же говорить о том, где в реальной практике может использоваться нахождение длины строки, то это, например, поле для ввода какого-нибудь текста, позволяющее определить размер статьи в режиме онлайн.
Каковы нюансы в работе функции strlen?
Следует учитывать, что функция вычисляет количество байт в строке string, а не привычное нам число символов. И тут всё зависит от кодировки:
В нашем случае русские буквы в юникоде занимают 2 байта, в результате чего длина одной буквы становится равной двум: 11 букв * 2 + 3 пробела = 25. Это важная особенность.
Кроме того, если в измеряемой нами строке символы отсутствуют, функция вернет значение 0. Также не стоит использовать strlen для расчёта длины массива, т. к. вернётся NULL.
Ещё существует функция iconv_strlen, позволяющая нам в качестве второго параметра указывать кодировку:
Как посчитать число слов в строке? Необходимость в этом тоже иногда возникает. В PHP для выполнения данной задачи есть функция str_word_count. Она имеет 2 основных параметра, которые обязательны. Первый — сама строка, число слов в которой нас интересует. Второй — формат, в котором будет выведено значение. Возможно использование и третьего параметра — charlist, в котором можно указывать список дополнительных символов, которые функция посчитает как слова. Но этот параметр необязателен, к тому же, обычно в таких излишествах нет надобности.
Что касается параметра format, то он способен принимать три значения: — 0 — просто возвращается количество найденных слов; — 1 — массив слов, входящих в строку; — 2 — массив со словами, причём индекс каждого слова — это его позиция в строке.
Используем strlen и конструкцию if else
В некоторых задачах на PHP нужно определить, превышает ли длина нашей строки какой-нибудь предел, например, десять. Такие задачки решаются через конструкцию if else:
Пожалуй, на этом всё, успешного вам обучения!
Интересуют продвинутые знания по PHP? Добро пожаловать на специализированный курс:
Функция strlen в php
Покажет количество байт в два раза больше, чем элементов!
Синтаксис функции strlen
Для понимания работы функции strlen нам понадобится несколько примеров:
Функция strlen и число в php
Для иллюстрации работы функции и получения результатов, нам потребуется функция var_dump в том числе, но давайте все по порядку.
Нам нужно число, над которым мы будем проводить наши изыскания!
Пусть это будет «123456»
Оборачиваем это число в функцию strlen:
Результат вывода длины числа через strlen:
Далее(для общего развития), чтобы узнать возвращаемые данные и тип переменной обернем эту конструкцию в var_dump и выведем с помощью echo
Вывод число(int) и strlen, что с числом, изначально имеющий тип int вернет тип «int» и значение «6», количество байт равно количеству символов.
Функция strlen и число(тип string) в php
Передадим в функцию strlen число тип string
Следующий эксперимент, передадим в функцию число с типом «string», если мы помести число в кавычки, то это уже будет строка, а не число, например давайте получим результат var_dump(‘123456’); :
Теперь эту строку поместим в strlen. Мы выяснили, что данное число имеет тип string, пропустим данные через strlen echo strlen(‘123456’) :
Узнаем тип возвращенных данных echo var_dump(strlen(‘123456’)); :
Вывод число(string) и strlen, что с числом, изначально имеющий тип string вернет тип «int» и значение «6», количество байт равно количеству символов.
Strlen и строка(тип string) utf-8 в php
Мы узнали, что эта строка, следующим действием пропустим эту строку через strlen:
echo strlen(‘Привет’) :
Логично было предположить, что функция вернет значение такое же как и var_dump. Теперь проверим тип возвращенных данных.
var_dump( strlen (‘Привет’) );
Вывод строка(string) и strlen, что со строкой, изначально имеющий тип string вернет тип «int» и значение «12», количество байт НЕ равно количеству символов.
кириллица + utf-8 и strlen
Это можно сделать так:
echo strlen(iconv(«UTF-8», «windows-1251», «Привет»));
Функции для работы со строками
Для получения информации о более сложной обработке строк обратитесь к функциями Perl-совместимых регулярных выражений. Для работы с многобайтовыми кодировками посмотрите на функции по работе с многобайтовыми кодировками.
Содержание
User Contributed Notes 24 notes
In response to hackajar yahoo
No string-to-array function exists because it is not needed. If you reference a string with an offset like you do with an array, the character at that offset will be return. This is documented in section III.11’s «Strings» article under the «String access and modification by character» heading.
I’m converting 30 year old code and needed a string TAB function:
//tab function similar to TAB used in old BASIC languages
//though some of them did not truncate if the string were
//longer than the requested position
function tab($instring=»»,$topos=0) <
if(strlen($instring)
I use these little doo-dads quite a bit. I just thought I’d share them and maybe save someone a little time. No biggy. 🙂
Just a note in regards to bloopletech a few posts down:
The word «and» should not be used when converting numbers to text. «And» (at least in US English) should only be used to indicate the decimal place.
Example:
1,796,706 => one million, seven hundred ninety-six thousand, seven hundred six.
594,359.34 => five hundred ninety four thousand, three hundred fifty nine and thirty four hundredths
/*
* example
* accept only alphanum caracteres from the GET/POST parameters ‘a’
*/
to: james dot d dot baker at gmail dot com
PHP has a builtin function for doing what your function does,
/**
Utility class: static methods for cleaning & escaping untrusted (i.e.
user-supplied) strings.
Any string can (usually) be thought of as being in one of these ‘modes’:
pure = what the user actually typed / what you want to see on the page /
what is actually stored in the DB
gpc = incoming GET, POST or COOKIE data
sql = escaped for passing safely to RDBMS via SQL (also, data from DB
queries and file reads if you have magic_quotes_runtime on—which
is rare)
html = safe for html display (htmlentities applied)
Always knowing what mode your string is in—using these methods to
convert between modes—will prevent SQL injection and cross-site scripting.
This class refers to its own namespace (so it can work in PHP 4—there is no
self keyword until PHP 5). Do not change the name of the class w/o changing
all the internal references.
Example usage: a POST value that you want to query with:
$username = Str::gpc2sql($_POST[‘username’]);
*/
Example: Give me everything up to the fourth occurance of ‘/’.
//
// string strtrmvistl( string str, [int maxlen = 64],
// [bool right_justify = false],
// [string delimter = «
\n»])
//
// splits a long string into two chunks (a start and an end chunk)
// of a given maximum length and seperates them by a given delimeter.
// a second chunk can be right-justified within maxlen.
// may be used to ‘spread’ a string over two lines.
//
I really searched for a function that would do this as I’ve seen it in other languages but I couldn’t find it here. This is particularily useful when combined with substr() to take the first part of a string up to a certain point.
?>
Example: Give me everything up to the fourth occurance of ‘/’.
The functions below:
Are correct, but flawed. You’d need to use the === operator instead:
Here’s an easier way to find nth.
I was looking for a function to find the common substring in 2 different strings. I tried both the mb_string_intersect and string_intersect functions listed here but didn’t work for me. I found the algorithm at http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Longest_common_substring#PHP so here I post you the function
Here’s a simpler «simplest» way to toggle through a set of 1..n colors for web backgrounds:
If you want a function to return all text in a string up to the Nth occurrence of a substring, try the below function.
(Pommef provided another sample function for this purpose below, but I believe it is incorrect.)
/*
// prints:
S: d24jkdslgjldk2424jgklsjg24jskgldjk24
1: d
2: d24jkdslgjldk
3: d24jkdslgjldk24
4: d24jkdslgjldk2424jgklsjg
5: d24jkdslgjldk2424jgklsjg24jskgldjk
6: d24jkdslgjldk2424jgklsjg24jskgldjk24
7: d24jkdslgjldk2424jgklsjg24jskgldjk24
*/
?>
Note that this function can be combined with wordwrap() to accomplish a routine but fairly difficult web design goal, namely, limiting inline HTML text to a certain number of lines. wordwrap() can break your string using
, and then you can use this function to only return text up to the N’th
.
You will still have to make a conservative guess of the max number of characters per line with wordwrap(), but you can be more precise than if you were simply truncating a multiple-line string with substr().
= ‘Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu dolor suscipit sem, tristique convallis ante ante id diam. Curabitur mollis, lacus vel gravida accumsan, enim quam condimentum est, vitae rutrum neque magna ac enim.’ ;
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin
ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis
mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin
ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis
mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu
dolor suscipit sem, tristique convallis ante ante id diam. Curabitur mollis, lacus vel gravida