Кол во символов в строке 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.

Источник

четверг, 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 количество символов подсчитать и определить свой талант

Дата публикации: 2017-06-23

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

От автора: краткость – сестра таланта, «засевшего» в Twitter! Сегодня я попытаюсь создать программный «тренажер», который позволит выработать у пользователей привычку изъясняться кратко. Для этого нужно научиться подсчитывать с помощью PHP количество символов.

Набираем форму

Сначала нам нужно набрать «форму». Так сказать, привести в тонус свои мозговые мышцы. Для этого потренируемся в верстке веб-формы для тренажера:

Так форма для счета знаков в строке выглядит в браузере:

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

Бесплатный курс по PHP программированию

Освойте курс и узнайте, как создать динамичный сайт на PHP и MySQL с полного нуля, используя модель MVC

В курсе 39 уроков | 15 часов видео | исходники для каждого урока

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

Обрабатываем

Теперь переходим к написанию обработчика для формы. Вот его первый вариант:

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

Чтобы определить длину текста, мы использовали функцию strlen(). В качестве параметров она принимает строку и возвращает число знаков в ней.

Хотя эта функция обладает одним серьезным недостатком: она считает не количество символов, а байт. Но в каждой из текстовых кодировок символ может занимать разное число байт. Например, в Unicode это может быть и два, и четыре.

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

Бесплатный курс по PHP программированию

Освойте курс и узнайте, как создать динамичный сайт на PHP и MySQL с полного нуля, используя модель MVC

В курсе 39 уроков | 15 часов видео | исходники для каждого урока

Нивелируем проблему кодировки

Чтобы «нивелировать» эту проблему, применим другую функцию – iconv_strlen(). В отличие от предыдущей эта позволяет посчитать число знаков с учетом используемой кодировки. В следующем примере демонстрируется разница количества символов в одной и той же строке, но в разных кодировках:

Источник

Функции для работы со строками

Для получения информации о более сложной обработке строк обратитесь к функциями Perl-совместимых регулярных выражений. Для работы с многобайтовыми кодировками посмотрите на функции по работе с многобайтовыми кодировками.

Содержание

User Contributed Notes 24 notes

In response to hackajar yahoo com,

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

Источник

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 не будет опубликован. Обязательные поля помечены *