php регистронезависимое сравнение строк
strnatcmp
(PHP 4, PHP 5, PHP 7, PHP 8)
strnatcmp — Сравнение строк с использованием алгоритма «natural order»
Описание
Эта функция реализует алгоритм сравнения, упорядочивающий алфавитно-цифровые строки подобно тому, как это сделал бы человек, такой алгоритм называется «natural ordering». Сравнение происходит с учётом регистра.
Список параметров
Возвращаемые значения
Примеры
Пример, показывающий отличие этого алгоритма от обычных функций сравнения (используемых в strcmp() ), приведён ниже:
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 5 notes
Can also be used with combination of a compare for an array nested value, like
There seems to be a bug in the localization for strnatcmp and strnatcasecmp. I searched the reported bugs and found a few entries which were up to four years old (but the problem still exists when using swedish characters).
This function has some interesting behaviour on strings consisting of mixed numbers and letters.
One may expect that such a mixed string would be treated as alpha-numeric, but that is not true.
var_dump(strnatcmp(’23’,’123′)); →
int(-1)
As expected, 23 xyz (string comparison, irregardless of string length)
var_dump(strnatcmp(‘2x’,’12y’)); →
int(-1)
Remarkable, 2x 12y (does a numeric comparison)
It seems to be splitting what is being compared into runs of numbers and letters, and then comparing each run in isolation, until it has an ordering difference.
Строковые функции в 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»!
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.
Учебник по PHP 4
Функции сравнения строкstrcmp()Эта функция сравнения строк. Она сравнивает две строки и возвращает: Функция является чувствительной к регистру, т.е. регистр символов влияет на результаты сравнений (поскольку сравнение происходит побайтово). strnatcasecmp()Производит «естественное» сравнение строк без учета регистра. Функция выполняет то же самое, что и strnatcmp(), только без учета регистра. similar_text()Эта функция производит определение схожести двух строк. Функция similar_text() определяет схожесть двух строк по алгоритму Оливера. Функция возвращает число символов, совпавших в строках str_first и str_second. Третий необязательный параметр передается по ссылке и в нем сохраняется процент совпадения строк.
levenshtein()Функция выполняет определение различия Левенштейна двух строк. Под понятием «различие Левенштейна» понимается минимальное число символов, которое требовалось бы заменить, вставить или удалить для того, чтобы превратить строку str1 в str2. Сложность алгоритма этой функции равна O(m*n), т.е. пропорциональна произведению длин строк str1 и str2, поэтому эта функция намного более быстрая, чем функция similar_text(). Как видим, у функции три вида синтаксиса. В первом случае функция возвращает число необходимых операций над символами строк для преобразования str1 в str2: Во втором случае добавляется три дополнительных параметра: стоимость операции вставки cost_ins, замены cost_rep и удаления cost_del. Естественно, функция в этом случае становится менее быстродействующей. Возвращается интегральный показатель сложности трансформации (ИПСТ). Число 21, между прочим, это 7*3 :). Т.е. ИПСТ равен произведению количества символов, необходимых для замены (а как мы посчитали в предыдущем примере их надобно 7) на стоимость, в этом случае, одной из операций. В этом примере, поскольку стоимость одинакова, не имеет значения, какую операцию брать. В случае, если стоимости различны, при вычисления ИПСТ берется наибольший. Т.е., если мы напишем в этом примере то функция вернет нам значение 42. Третий вариант позволяет указать функцию, используемую для расчета сложности трансформации.
Если Вам нужна частная профессиональная консультация от авторов многих книг Кузнецова М.В. и Симдянова И.В., добро пожаловать в наш Консультационный Центр SoftTime. strcasecmpstrcasecmp — Бинарно-безопасное сравнение строк без учета регистра ОписаниеБинарно-безопасное сравнение строк без учета регистра. Список параметровВозвращаемые значенияПримерыПример #1 Пример использования strcasecmp() Смотрите такжеКоментарии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! A simple multibyte-safe case-insensitive string comparison: ?> Caveat: watch out for edge cases like «ß». 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» ; ?> This might be incredibly obvious to most people, but hopefully it will clarify the calculation process for some others.
|