Количество символов в тексте php
четверг, 21 июня 2012 г.
Считаем количество символов в строке. PHP
В данной статье я рассмотрю подсчет символов в строке. В обычном случае может применяться стандартная функция strlen(). Но если у вас кириллица, то есть используется кодировка UTF-8, данные функции будут работать не так, как бы нам хотелось.
Приведем небольшой пример:
if ( isset ($_POST[ ‘fio’ ]) && strlen($_POST[ ‘fio’ ]’)
echo «Слишком мало информации в поле ‘Фамилия, имя, отчество’!» ;
>
В данном примере мы проверяем данные, отправленные с текстового поля с name = ‘fio’ и если длина строки не превышает 8 символов, надеемся увидеть сообщение о том, что пользователь ввел мало информации и, естественно, не обрабатывать данные дальше.
Если пользователь вводит латиницу или спец. симаолы, то данный пример работает отлично.
Однако, если пользователь, например, будет работать с кириллицей (что нам и нужно), то при вводе даже 5 символов данное условие не сработает.
Посмотрим, что же тут не так. Введём, например, в тестовое поле слово ‘тест’ и обработаем следующим образом:
Получаем: Количество введённых символов: 8
Причина такого расхождения в ожидаемой и реальной длине — размер кириллических символов в UTF-8: по 2 байта вместо 1 для латинских. Функция strlen() считает длину строки в байтах, а не в буквах, и если буква занимает два байта, она засчитывается за две.
Решение первое. Используем функцию iconv_strlen(), которая возвращает число символов в строке.
Синтаксис функции:
int iconv_strlen (string str [, string charset])
В отличие от strlen(), iconv_strlen() подсчитывает число символов на основании кодировки, переданной во втором не обязательном параметре, а не как простой подсчёт байтов в строке.
Необязательный параметр charset указывает кодировку, в которой следует интерпретировать строки. Если он опущен, по умолчанию, будет использоваться кодировка, определённая в iconv.internal_charset.
Теперь, если мы перепишем наш последний пример следующим образом, то получим:
Ввод пользователя: ‘тест’.
Получаем: Количество введённых символов: 4
Решение второе. Используем функцию mb_strlen().
Проверим работу этой функции на нашем примере:
Ввод пользователя: ‘тест’.
Получаем: Количество введённых символов: 4
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 посчитать и вывести количество символов в статье?
2015-06-01 / Вр:01:30 / просмотров: 8423
Совсем недавно заказчик поставил мне цель написать скрипт на PHP, умеющий высчитывать все символы, которые написал зарегистрированный пользователь. Сайт заказчика был сделан на WordPress.
Что ж, друзья, у меня получилось написать такой скрипт и теперь пользователь может видеть на сайте количество написанных им символов и сколько заработанных у него балов.
В результате вы увидите на странице надпись:
Количество символов: 37
Вывод текста: Я рад видеть вас на блоге BlogGood.ru
Давайте разберем код:
Строка №1 – создаем переменную, в которую вставляем текст.
Обратите внимание как заполнено:
$text – это переменная, в которую мы прописали текст ( см. чуть выше )
utf-8 – кодировка.
Строка №4 – выводим количество символов с помощью оператора echo.
Строка №5 – выводим текст.
Строку №5 можно удалить, ее я вам показал только для примера, что считает скрипт.
В строке№3 я указал, что если есть пробел, тогда нужно его заменить на пустоту (без пробелов)
В результате вы увидите на странице надпись:
Количество символов: 31
Вывод текста: ЯрадвидетьваснаблогеBlogGood.ru
Строку №7 можно удалить, ее я вам показал только для примера, что считает скрипт:
Кстати, если кто-то заинтересовался скриптом, который будет выводить имя пользователя, количество символов на всех статьях и делать подсчет бонусов за количество символов, обращайтесь – вы сможете купить его у меня по доступной цене.
count_chars
(PHP 4, PHP 5, PHP 7, PHP 8)
count_chars — Возвращает информацию о символах, входящих в строку
Описание
Подсчитывает количество вхождений каждого из символов с ASCII-кодами в диапазоне (0..255) в строке string и возвращает эту информацию в различных форматах.
Список параметров
Смотрите возвращаемые значения.
Возвращаемые значения
Список изменений
Версия | Описание |
---|---|
8.0.0 | До этой версии функция возвращала false в случае возникновения ошибки. |
Примеры
Пример #1 Пример использования count_chars()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 11 notes
If you have problems using count_chars with a multibyte string, you can change the page encoding. Alternatively, you can also use this mb_count_chars version of the function. Basically it is mode «1» of the original function.
count_chars for multibyte supported.
// Require (n) unique characters in a string
// Modification of a function below which ads some flexibility in how many unique characters are required in a given string.
$pass = ‘123456’ ; // true
$pass = ‘111222’ ; // false
I have no idea where this could be used, but it’s quite fun
This function is great for input validation. I frequently need to check that all characters in a string are 7-bit ASCII (and not null). This is the fastest function I have found yet:
Here’s a function to count number of strings in a string. It can be used as a simple utf8-enabled count_chars (but limited to a single mode).
Another approach to counting unicode chars.
Checking that two strings are anagram:
// Usefulness of the two functions
Here are some more experiments on this relatively new and extremely handy function.
= ‘I have never seen ANYTHING like that before! My number is «4670-9394».’ ;
#The result looks like
#The character » » has appeared in this string 11 times.
#This shows that ’70 is not the same as 36′
?>
As we can see above:
1)If you cares only about what is in the string, use count_chars($string, 1) and it will return an (associative?) array of what shows up only.
2) Either I misunderstood what the manul actually said, or it does not work the way it described: count_chars($strting, 3) actually returned a string of what characters are in the string, not a string of their byte-values (which is great because a string of numbers would be much harder to handle);
3)This is a short version of password checking: get the original string’s length, then compare with the length of the string returned by count_chars($string,3).
4) Final trick: now we have a primitive way to count the number of words in a string! (or do we have a fuction for that already?)
this code can find each characters count