php сравнение строк utf 8

Русские Блоги

Одиннадцать: Сравнение строк PHP

Один: Резюме

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

2. strcasecmp () сравнивает коды ASCALL без учета регистра

3. strnatcmp () выполняет сортировку в числовом порядке, даже если сравниваемые две строки являются строками.

По умолчанию используется сортировка ASCALL, например, когда 2 сравнивается с 10, 2 больше 10

4. strnatcasecmp () не чувствителен к регистру, отсортировано в числовом порядке.

5. strapn (строка, список символов, начало, длина): возвращает количество символов, которые нужно найти в строке.

Вычислить, что все символы в строке находятся в указанном наборе символов Длина первой подстроки
Проверяемая строка: маленькая строка
Проверьте список строк: большие строки, найдите маленькие строки из этого
Начальная позиция проверяемой строки, длина проверяемой строки, необязательно или нет

6. Функция strlen () проверяет длину строки.

7. substr_count (строка, строка для тестирования): возвращает количество раз, когда проверяемая строка появляется в другой строке.

9. stristr () не чувствителен к регистру

10. strpos () возвращает позицию символа из большой строки, начиная с 0.

11. strrpos () возвращает предпоследнюю позицию первого вхождения символа.

Источник

Строковые функции в PHP. Сравнение строк в PHP

В PHP для сравнения строк используется несколько функций. В этой статье мы поговорим о том, как сравнить строки в PHP.

Итак, для сравнения можно использовать: — strcmp(); — strncmp(); — strcasecmp(); — strncasecmp(); — strnatcmp(); — strnatcasecmp(); — similar_text(); — levenshtein().

1. strcmp()

Данная функция сравнивает 2 строки в PHP и возвращает: — 1, когда строка str1 лексикографически больше, чем str2; — 0, когда строки полностью совпадают; — 1, когда строка str1 лексикографически меньше str2.

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

Пример работы strcmp() в PHP:

2. strncmp()

Данная функция отличается от strcmp() прежде всего тем, что сравнивает первые len байтов, т. е. начала строк. А когда len меньше длины наименьшей из строк, строки сравниваются целиком.

3. strcasecmp()

4. strncasecmp()

strncasecmp() сравнивает начала строк, не учитывая регистр.

5. strnatcmp()

Выполняет «естественное» сравнение строк в PHP. Можно сказать, что функция имитирует сравнение строк человеком. Например, если мы будем сравнивать файлы pict20.gif, pict1.gif, pict2.gif, pict10.gif, то при обычной сортировке получим следующее расположение: pict1.gif, pict10.gif, pict2.gif, pict20.gif. А вот естественная сортировка с помощью strnatcmp() даст результат, который более привычен человеку: pict1.gif, pict2.gif, pict10.gif, pict20.gif.

Результат работы в PHP:

6. strnatcasecmp()

Выполняет вышеупомянутое «естественное» сравнение строк, но уже не учитывая регистр.

7. similar_text()

Определяет схожесть двух строк по алгоритму Оливера. Возвращается число символов, совпавших в строках str_second и str_first. Третий параметр необязателен — он передаётся по ссылке, плюс в нём сохраняется совпадение строк в процентах.

8. levenshtein()

Определяет различие Левенштейна при сравнении двух строк в PHP.

Различие Левенштейна — минимальное количество символов, которое нужно заменить, удалить или вставить, чтобы превратить строку str1 в str2.

Хотите знать больше? Записывайтесь на курс «Backend-разработчик на PHP»!

Источник

strcasecmp

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

strcasecmp — Бинарно-безопасное сравнение строк без учёта регистра

Описание

Бинарно-безопасное сравнение строк без учёта регистра. Сравнение не зависит от локали; только буквы ASCII сравниваются без учёта регистра.

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

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

Примеры

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

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

User Contributed Notes 4 notes

A simple multibyte-safe case-insensitive string comparison:

?>

Caveat: watch out for edge cases like «ß».

The sample above is only true on some platforms that only use a simple ‘C’ locale, where individual bytes are considered as complete characters that are converted to lowercase before being differentiated.

Don’t base your code on a specific non null value returned by strcmp() or strcasecmp(): it is not portable. Just consider the sign of the result and be sure to use the correct locale!

I didn’t see any explanation in the documentation as to precisely how the positive/negative return values are calculated for unequal strings.

After a bit of experimentation it appears that it’s the difference in alphabetical position of the first character in unequal strings.

For example, the letter ‘z’ is the 26th letter while the letter ‘a’ is the 1st letter:

= «zappl» ;
$apple = «apple» ;

?>

This might be incredibly obvious to most people, but hopefully it will clarify the calculation process for some others.

Источник

Сравнение строки UTF-8

Я пытаюсь сравнить две строки, можно сказать, Эмили и Зои. Ну ‘E’ доходит до ‘Z’, но на ASCII-диаграмме Z приходит до É, поэтому нормальный if ( str1 > str2 ) не будет работать.

Я пытался с if (strcmp(str1,str2) > 0) все еще не работает. Поэтому я ищу способ сравнения строк с символами UTF-8.

ВАЖНЫЙ

Сортировка с помощью символов без акцента в PHP 5.2

Вы можете попробовать преобразовать обе строки в ASCII с помощью кнопок iconv () и // TRANSLIT, чтобы избавиться от акцентированных символов;

Затем сделайте сравнение

Смотрите документацию здесь:

[обновлено, в ответ на замечание @ Esailija] Я упустил из виду проблему // TRANSLIT, переводящей акцентированные персонажи неожиданными способами. Эта проблема упоминается в этом вопросе: php iconv translit для удаления акцентов: не работает как исключено?

Чтобы сделать подход «iconv ()», я добавил пример кода ниже, который разбивает все символы без слов из результирующей строки, используя preg_replace ().

Для этого нет собственного способа, но расширение PECL: http://php.net/manual/de/class.collator.php

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

Я просто использую функцию mb_strpos и просматриваю результаты. Я предполагаю, что это будет так близко, как вы можете получить нативное сравнение строк UTF8:

Источник

strcmp

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

strcmp — Бинарно-безопасное сравнение строк

Описание

Эта функция учитывает регистр символов.

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

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

Примеры

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

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

User Contributed Notes 29 notes

i hope this will give you a clear idea how strcmp works internally.

On Debian Lenny (and RHEL 5, with minor differences), I get this:

Pascal-style string:
ps = /var/www
str_split(ps) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w )

Normal results of comparison:
sz == ps = false
strcmp(sz,ps) = 1

Comparison with trim()’d zero-terminated string:
trim(sz) = /var/www
str_split(trim(sz)) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w )
trim(sz) == ps = true
strcmp(trim(sz),ps) = 0

Note a difference between 5.2 and 5.3 versions

Of course, you never need to use array as a parameter in string comparisions.

Don’t forget the similar_text() function.

echo » ;
?>

In Apache/2.4.37 (Win32) OpenSSL/1.1.1 PHP/7.2.12 produces the following results:

Some notes about the spanish locale. I’ve read some notes that says «CH», «RR» or «LL» must be considered as a single letter in Spanish. That’s not really tru. «CH», «RR» and «LL» where considered a single letter in the past (lot of years ago), for that you must use the «Tradictional Sort». Nowadays, the Academy uses the Modern Sort and recomends not to consider anymore «CH», «RR» and «LL» as a single letter. They must be considered two separated letters and sort and compare on that way.

Since it may not be obvious to some people, please note that there is another possible return value for this function.

strcmp() will return NULL on failure.

This has the side effect of equating to a match when using an equals comparison (==).
Instead, you may wish to test matches using the identical comparison (===), which should not catch a NULL return.

Please use strcmp() carefully when comparing user input, as this may have potential security implications in your code.

For instance:
= «foo» ; // length 3
$b = «» ; // empty string
$c = «barbar» ; // length 6

Vulnerability (in PHP >=5.3) :

Natural sort is also supported, use setAttribute to set Collator::NUMERIC_COLLATION to Collator::ON.

I have tried the strcmp function. Pls be very carefull. The string comparison must exactly «equal». So many people had confused.

My program read a string from test.txt file to get the
«[company name]» string.

// get contents of a file into a string
$filename = «test.txt»;
$fd = fopen ($filename, «rb»);
$contents = fread ($fd, filesize ($filename));

I hope the above example will help you.

In cases when you need to compare a line from a just parsed file stream to match a user-defined «nametag» (useful for parsing ini and configuration files), keep in mind the ‘end of line’ tags as well:

// nametag to look for in a file (notice a required «\r\n» at the end)
$nametag = «[System]\r\n»;

php dot or dot die at phpuser dot net wrote that he had an unexpected difference in comparing between case sensitive and insensitive. They key there is that the case insensitive comparison converts both strings to lowercase before comparing. Since the underscore character is in a different place when compared to an uppercase or lowercase string, the result is different.

There is no ‘clear’ order of punctuation and other characters in or around the alphabet. Most code assumes ASCII order in which case there are several characters before both upper- and lowercase, a few inbetween, and some after both upper- and lowercase.

Note also many other/older implementations of sorting sort accented character wrong since they appear after all other alphabetical characters in most charactersets. There is probably a function in PHP to take this into account though.

Therefore I would not recommend to make a detailed assumption on how punctuation and other characters sort in relation to alphabetical characters. If sorting these characters at a specific place and in a specific order is important for you, you should probably write a custom string comparison function that does it the way you want. Usually it’s sufficient to have a consistent sorting order though, which is what you get by using either strcmp, or strcasecmp consistently.

For those that are confused about the way this function works:

If we were searching through an alphabetically sorted list we’d have a numerical index ($i) and compare the search string ($sstr) against each member of the string list ($slist), using strcmp we can check whether to go «up»($i++) or «down»($i—) through this list.

Sometimes when you compare two strings that look «the same», you will find that they aren’t. If you don’t want to bother finding out why, then this is a simple solution:

Converting the strings to md5 is also a nice method to see if they’re equal.

Источник

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

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