php число символов в строке

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.

Источник

strlen

(PHP 4, PHP 5, PHP 7, PHP 8)

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

Описание

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

Строка ( string ), для которой измеряется длина.

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

Примеры

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

Примечания

Функция strlen() возвратит количество байт, а не число символов в строке.

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

User Contributed Notes 8 notes

I want to share something seriously important for newbies or beginners of PHP who plays with strings of UTF8 encoded characters or the languages like: Arabic, Persian, Pashto, Dari, Chinese (simplified), Chinese (traditional), Japanese, Vietnamese, Urdu, Macedonian, Lithuanian, and etc.
As the manual says: «strlen() returns the number of bytes rather than the number of characters in a string.», so if you want to get the number of characters in a string of UTF8 so use mb_strlen() instead of strlen().

// the Arabic (Hello) string below is: 59 bytes and 32 characters
$utf8 = «السلام علیکم ورحمة الله وبرکاته!» ;

The easiest way to determine the character count of a UTF8 string is to pass the text through utf8_decode() first:

We just ran into what we thought was a bug but turned out to be a documented difference in behavior between PHP 5.2 & 5.3. Take the following code example:

?>

This is because in 5.2 strlen will automatically cast anything passed to it as a string, and casting an array to a string yields the string «Array». In 5.3, this changed, as noted in the following point in the backward incompatible changes in 5.3 (http://www.php.net/manual/en/migration53.incompatible.php):

«The newer internal parameter parsing API has been applied across all the extensions bundled with PHP 5.3.x. This parameter parsing API causes functions to return NULL when passed incompatible parameters. There are some exceptions to this rule, such as the get_class() function, which will continue to return FALSE on error.»

So, in PHP 5.3, strlen($attributes) returns NULL, while in PHP 5.2, strlen($attributes) returns the integer 5. This likely affects other functions, so if you are getting different behaviors or new bugs suddenly, check if you have upgraded to 5.3 (which we did recently), and then check for some warnings in your logs like this:

strlen() expects parameter 1 to be string, array given in /var/www/sis/lib/functions/advanced_search_lib.php on line 1028

If so, then you are likely experiencing this changed behavior.

When checking for length to make sure a value will fit in a database field, be mindful of using the right function.

There are three possible situations:

1. Most likely case: the database column is UTF-8 with a length defined in unicode code points (e.g. mysql varchar(200) for a utf-8 database).

Find the character set used, and pass it explicitly to the length function.

There’s a LOT of misinformation here, which I want to correct! Many people have warned against using strlen(), because it is «super slow». Well, that was probably true in old versions of PHP. But as of PHP7 that’s definitely no longer true. It’s now SUPER fast!

I created a 20,00,000 byte string (

20 megabytes), and iterated ONE HUNDRED MILLION TIMES in a loop. Every loop iteration did a new strlen() on that very, very long string.

The result: 100 million strlen() calls on a 20 megabyte string only took a total of 488 milliseconds. And the strlen() calls didn’t get slower/faster even if I made the string smaller or bigger. The strlen() was pretty much a constant-time, super-fast operation

So either PHP7 stores the length of every string as a field that it can simply always look up without having to count characters. Or it caches the result of strlen() until the string contents actually change. Either way, you should now never, EVER worry about strlen() performance again. As of PHP7, it is super fast!

Here is the complete benchmark code if you want to reproduce it on your machine:

Источник

Полезные PHP коды — для новичков

При написании кода в PHP есть задачи, которые встречаются чаще остальных или просто как-то выделяются из общего множества. В этой статье поговорим о некоторых из них.

Тут собрана лишь малая часть, и наверное это не последняя статья на тему несложных популярных задачек в PHP. Кроме того, я планирую дополнять эту статью.

Короткая запись операторов присваивания

Время выполнения PHP скрипта

Округление дробных чисел

Округление до целых

Чтобы округлить число в php существует несколько функций:

Округление до дробных

Округление последнего числа происходит как в математики: если следующее больше или равно 5 то в большую сторону, в остальных случаях в меньшую.

Целая часть и остаток от деления чисел

Чтобы получить остаток от деления можно воспользоваться оператором % :

Числа кратные к N или каждый N-ый блок в цикле

Нужно разделить число на число и если остатка нет, то первое число делиться нацело на второе, а значит кратное.

Где применить эту кратность?

Допустим, есть цикл записей и нужно к каждому третьему блоку добавить отдельный css класс. Тут-то кратность нам и поможет.

Форматирование чисел (денег) в PHP

Форматирует число с разделением групп.

number(обязательный)
Число, которое нужно отформатировать.

decimals
Сколько знаков после запятой показывать.

dec_point
Разделитель для дробной части.

Для форматирования с учетом языка сайта в WordPress есть специальная функция number_format_i18n()

Для вывода денежных величин используйте похожую функцию money_format()

Как получить ключи или значения ассоциативного PHP массива

Это может пригодится когда нужно сделать поиск по ключам массива. В PHP такой встроенной функции нет.

Создаем массив из диапазона чисел или букв

Как получить максимальное или минимальное число из массива в PHP

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

Как получить часть строки (подстроку)

Однако нужно знать, что скорость их работы в разы ниже: substr() работает с одинаковой скоростью для строки любой длинны. А вот mb_substr() и iconv_substr() работают тем медленнее чем длине строка в них указывается. В среднем они в 5-10 раз медленнее, однако альтернатив нет, если нужно обработать кириллицу, придется использовать их.

Количество символов в строке

Как посчитать сколько раз встречается одна строка в другой

Удаление символов внутри строки

Сделать это можно многими способами, но самый простой это функция str_replace() :

Удаление символов на концах строки

Также, не все знают что есть аналогичные функции:

Удаление пустых символов на концах строки
Удаление указанных символов в начале и конце строки

Как перевернуть строку в PHP

День недели и месяц по-русски на PHP

Месяц по-русски

День недели

Есть что добавить? Милости прошу в комментарии.

Источник

Как на php посчитать и вывести количество символов в статье?

2015-06-01 / Вр:01:30 / просмотров: 8435

Совсем недавно заказчик поставил мне цель написать скрипт на PHP, умеющий высчитывать все символы, которые написал зарегистрированный пользователь. Сайт заказчика был сделан на WordPress.
Что ж, друзья, у меня получилось написать такой скрипт и теперь пользователь может видеть на сайте количество написанных им символов и сколько заработанных у него балов.

php число символов в строке. Смотреть фото php число символов в строке. Смотреть картинку php число символов в строке. Картинка про php число символов в строке. Фото php число символов в строке

В результате вы увидите на странице надпись:

Количество символов: 37
Вывод текста: Я рад видеть вас на блоге BlogGood.ru

Давайте разберем код:

Строка №1 – создаем переменную, в которую вставляем текст.

Обратите внимание как заполнено:

$text – это переменная, в которую мы прописали текст ( см. чуть выше )
utf-8 – кодировка.

Строка №4 – выводим количество символов с помощью оператора echo.

Строка №5 – выводим текст.

Строку №5 можно удалить, ее я вам показал только для примера, что считает скрипт.

В строке№3 я указал, что если есть пробел, тогда нужно его заменить на пустоту (без пробелов)
В результате вы увидите на странице надпись:

Количество символов: 31
Вывод текста: ЯрадвидетьваснаблогеBlogGood.ru

Строку №7 можно удалить, ее я вам показал только для примера, что считает скрипт:

Кстати, если кто-то заинтересовался скриптом, который будет выводить имя пользователя, количество символов на всех статьях и делать подсчет бонусов за количество символов, обращайтесь – вы сможете купить его у меня по доступной цене.

Источник

str_word_count

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

str_word_count — Возвращает информацию о словах, входящих в строку

Описание

Для этой функции «слово» обозначает строку с алфавитными символами, зависящую от локали, которая также может содержать символы «‘» и «-«, но не может начинаться с них. Обратите внимание, что многобайтовые языковые стандарты не поддерживаются.

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

Список дополнительных символов, которые будут рассматриваться как «слово»

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

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

Примеры

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

= «Hello fri3nd, you’re
looking good today!» ;

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

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

User Contributed Notes 32 notes

/***
* This simple utf-8 word count function (it only counts)
* is a bit faster then the one with preg_match_all
* about 10x slower then the built-in str_word_count
*
* If you need the hyphen or other code points as word-characters
* just put them into the [brackets] like [^\p\p\’\-]
* If the pattern contains utf-8, utf8_encode() the pattern,
* as it is expected to be valid utf-8 (using the u modifier).
**/

We can also specify a range of values for charlist.

Array ( [0] => Hello [1] => fri3nd [2] => you’re [3] => looking [4] => good [5] => today [6] => look123 [7] => ing )

Here is a count words function which supports UTF-8 and Hebrew. I tried other functions but they don’t work. Notice that in Hebrew, ‘»‘ and ‘\» can be used in words, so they are not separators. This function is not perfect, I would prefer a function we are using in JavaScript which considers all characters except [a-zA-Zא-ת0-9_\’\»] as separators, but I don’t know how to do it in PHP.

I removed some of the separators which don’t work well with Hebrew («\x20», «\xA0», «\x0A», «\x0D», «\x09», «\x0B», «\x2E»). I also removed the underline.

Hi this is the first time I have posted on the php manual, I hope some of you will like this little function I wrote.

It returns a string with a certain character limit, but still retaining whole words.
It breaks out of the foreach loop once it has found a string short enough to display, and the character list can be edited.

This function doesn’t handle accents, even in a locale with accent.
echo str_word_count ( «Is working» ); // =2

//To get an accurate word count in English, some diacritical marks have
// to be added for words like née, Chloë, naïve, coöpt, façade, piñata, etc.
$count = str_word_count($str, 0, ‘éëïöçñÉËÏÖÇÑ’);

//To get the word count for any European language using a Roman alphabet:
$count = str_word_count($str, 0, ‘äëïöüÄËÏÖÜáǽćéíĺńóŕśúźÁǼĆÉÍĹŃÓŔŚÚŹ’.
‘àèìòùÀÈÌÒÙãẽĩõñũÃẼĨÕÑŨâêîôûÂÊÎÔÛăĕğĭŏœ̆ŭĂĔĞĬŎŒ̆Ŭ’.
‘āēīōūĀĒĪŌŪőűŐŰąęįųĄĘĮŲåůÅŮæÆøØýÝÿŸþÞẞßđĐıIœŒ’.
‘čďěľňřšťžČĎĚĽŇŘŠŤŽƒƑðÐłŁçģķļșțÇĢĶĻȘȚħĦċėġżĊĖĠŻʒƷǯǮŋŊŧŦ’);

For spanish speakers a valid character map may be:

preg_match_all based function to mimic str_word_count behavior:

This example may not be pretty, but It proves accurate:

I needed a function which would extract the first hundred words out of a given input while retaining all markup such as line breaks, double spaces and the like. Most of the regexp based functions posted above were accurate in that they counted out a hundred words, but recombined the paragraph by imploding an array down to a string. This did away with any such hopes of line breaks, and thus I devised a crude but very accurate function which does all that I ask it to:

I was interested in a function which returned the first few words out of a larger string.

In reality, I wanted a preview of the first hundred words of a blog entry which was well over that.

I found all of the other functions which explode and implode strings to arrays lost key markups such as line breaks etc.

So, this is what I came up with:

The idea behind it? Use str_word_count to identify the nth word, then use str_word_count to identify the position of that word within the string, then use substr to extract up to that position.

This is my own version of to get SEO meta description from wordpress post content. it is also generic usage function to get the first n words from a string.

to count words after converting a msword document to plain text with antiword, you can use this function:

Here is a php work counting function together with a javascript version which will print the same result.

If you are looking to count the frequency of words, try:

This needs improvement, but works well as is.

= ‘http://www.php.net/’ ;
// or use a local file, see file_get_contents() for valid filenames and restrictions.

Источник

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

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