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

Источник

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

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

Совсем недавно заказчик поставил мне цель написать скрипт на 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.

Источник

substr_count

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

substr_count — Возвращает число вхождений подстроки

Описание

Эта функция не подсчитывает перекрывающиеся подстроки. Смотрите пример ниже!

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

Строка, в которой ведётся поиск

Смещение начала отсчёта. Если задано отрицательное значение, отсчёт позиции будет произведён с конца строки.

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

Эта функция возвращает целое число ( int ).

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

Примеры

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

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

User Contributed Notes 10 notes

500KB string on our web server. It found 6 occurrences of the needle I was looking for in 0.0000 seconds. Yes, it ran faster than microtime() could measure.

Looking to give it a challenge, I then ran it on a Mac laptop from 2010 against a 120.5MB string. For one test needle, it found 2385 occurrences in 0.0266 seconds. Another test needs found 290 occurrences in 0.114 seconds.

Long story short, if you’re wondering whether this function is slowing down your script, the answer is probably not.

Making this case insensitive is easy for anyone who needs this. Simply convert the haystack and the needle to the same case (upper or lower).

To account for the case that jrhodes has pointed out, we can change the line to:

array (
0 => «mystringth»,
1 => «atislong»
);

It was suggested to use

instead of the function described previously, however this has one flaw. For example this array:

array (
0 => «mystringth»,
1 => «atislong»
);

If you are counting «that», the implode version will return 1, but the function previously described will return 0.

Yet another reference to the «cgcgcgcgcgcgc» example posted by «chris at pecoraro dot net»:

Your request can be fulfilled with the Perl compatible regular expressions and their lookahead and lookbehind features.

This will handle a string where it is unknown if comma or period are used as thousand or decimal separator. Only exception where this leads to a conflict is when there is only a single comma or period and 3 possible decimals (123.456 or 123,456). An optional parameter is passed to handle this case (assume thousands, assume decimal, decimal when period, decimal when comma). It assumes an input string in any of the formats listed below.

below was suggested a function for substr_count’ing an array, yet for a simpler procedure, use the following:

Unicode example with «case-sensitive» option;

In regards to anyone thinking of using code contributed by zmindster at gmail dot com

Please take careful consideration of possible edge cases with that regex, in example:

This would cause a infinite loop and for example be a possible entry point for a denial of service attack. A correct fix would require additional code, a quick hack would be just adding a additional check, without clarity or performance in mind:

Источник

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

Источник

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

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