функция сравнения строк 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.
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.
similar_text
(PHP 4, PHP 5, PHP 7, PHP 8)
similar_text — Вычисляет степень похожести двух строк
Описание
Список параметров
Изменение порядка string1 и string2 может привести к другому результату; см, пример ниже.
При передаче по ссылке третьего аргумента, similar_text() присваивает ему степень похожести двух строк в процентах, деля результат similar_text() на среднее число длин заданных строк 100 раз.
Возвращаемые значения
Возвращается количество совпадающих символов в двух строках.
Количество совпадающих символов вычисляется путём нахождения самой длинной первой общей подстроки, а затем делает это для префиксов и суффиксов рекурсивно. Добавляются длины всех найденных общих подстрок.
Примеры
Пример #1 Пример использования similar_text() с заменой аргументов
В этом примере показано, что изменение порядка аргументов string1 и string2 может дать разные результаты.
Результатом выполнения данного примера будет что-то подобное:
Смотрите также
User Contributed Notes 13 notes
Be aware when using this function, that the order of passing the strings is very important if you want to calculate the percentage of similarity, in fact, altering the variables will give a very different result, example :
= ‘PHP IS GREAT’ ;
$var_2 = ‘WITH MYSQL’ ;
Please note that this function calculates a similarity of 0 (zero) for two empty strings.
Recursive algorithm usually is very elegant one. I found a way to get better precision without the recursion. Imagine two different (or same) length ribbons with letters on each. You simply shifting one ribbon to left till it matches the letter the first.
$str1 = ‘12345678901234567890’ ;
$str2 = ‘12345678991234567890’ ;
Note that this function is case sensitive:
= ‘Hello’ ;
$var2 = ‘Hello’ ;
$var3 = ‘hello’ ;
Actually similar_text() is not bad.
it works good. But before processing i think is a good way to make a little mod like this
$var_1 = strtoupper(«doggy»);
$var_2 = strtoupper(«Dog»);
The speed issues for similar_text seem to be only an issue for long sections of text (>20000 chars).
I found a huge performance improvement in my application by just testing if the string to be tested was less than 20000 chars before calling similar_text.
20000+ took 3-5 secs to process, anything else (10000 and below) took a fraction of a second.
Fortunately for me, there was only a handful of instances with >20000 chars which I couldn’t get a comparison % for.
If you have reserved names in a database that you don’t want others to use, i find this to work pretty good.
I added strtoupper to the variables to validate typing only. Taking case into consideration will decrease similarity.
Well, as mentioned above the speed is O(N^3), i’ve done a longest common subsequence way that is O(m.n) where m and n are the length of str1 and str2, the result is a percentage and it seems to be exactly the same as similar_text percentage but with better performance. here’s the 3 functions i’m using..
//this table will be used to compute the LCS-Length, only 128 chars per string are considered
$LCS_Length_Table = array(array( 128 ),array( 128 ));
To calculate the percentage of similarity between two strings without depending on the order of the parameters and be case insensitive, I use this function based on levenshtein’s distance:
?>
This will always return a number between 0 and 1, representing the percentage, for instance 0.8 represents 80% similar strings.
If you want this to be case-sensitive, just remove the strtoupper() functions.
Функция сравнения строк php
Эта функция сравнивает две строки посимвольно (точнее, бобайтово) и возвращает:
Так как сравнение идет побайтово, то регистр символов влияет на результаты сравнений.
Безопасное для обработки данных в двоичной форме сравнение 2 строк со смещением, с учетом или без учета регистра (PHP 5)
substr_compare() сравнивает строку main_str начиная с символа, номер которого задан аргументом offset, со строкой str. В сравнении участвуют максимум length символов.
Возвращает число 0 если она больше str, и 0 если строки равны. Если length больше или равен длине main_str и offset передан, substr_compare() выводит предупреждение и возвращает FALSE.
Если case_sensitivity имеет значение TRUE, сравнение выполняется с учетом регистра.
Пример использования substr_compare()
Сравнивает начала строк.
Синтаксис:
Эта функция отличается от strcmp() тем, что сравнивает не все слово целиком, а первые len байтов. В случае, если len меньше длины наименьшей из строк, то строки сравниваются целиком.
Эта функция сравнивает две строки посимвольно (точнее, бобайтово) и возвращает:
Так как сравнение идет побайтово, то регистр символов влияет на результаты сравнений.
Сравнивает строки без учета регистра.
Синтаксис:
То же самое, что и strcmp(), только при работе не учитывается регистр букв.
Сравнивает начала строк без учета регистра.
Синтаксис:
Функция strncasecmp() является комбинацией функций strcasecmp() и strncmp().
Производит «естественное» сравнение строк.
Синтаксис:
Данная функция имитирует сравнение строк, которое использовал бы человек.
Данный скприпт выведет следующее:
Производит «естественное» сравнение строк без учета регистра.
Синтаксис:
То же, что и strnatcmp(), только игнорирует регистр.
Производит определение схожести двух строк.
Синтаксис:
Определение различия Левенштейна двух строк.
Синтаксис:
Первая форма функции возвращает число необходимых операций над символами строк для трансформации str1 в str2.
Вторая форма имеет три дополнительных параметра: стоимость операции вставки, замены и удаления, что делает ее более адаптированной для вычисления, но при этом менее быстродействующей. Возвращается интегральный показатель сложности трансформации.
Третий вариант позволяет указать функцию, используемую для расчета сложности трансформации.
Функция cost вызывается со следующими аргументами:
применяемая операция (вставить, изменить, удалить): «I*quot;, «R», «D»;
фактический символ первой строки
фактический символ второй строки
оставшаяся длина строки 1
оставшаяся длина строки 2
Сравнение строк с учетом текущей локали (PHP 4 >= 4.0.5, PHP 5)
Возвращает положительное число если str1 меньше, чем str2; отрицательное число если str1 больше, чем str2, и 0 если строки равны. strcoll() при сравнении использует установки текущей локали. Если установлена локаль C или POSIX, эта функция аналогична strcmp().
Обратите внимание, что эта функция учитывает регистр символов, и, в отличие от strcmp() не безопасна для обработки данных в двоичной форме.
Замечание: strcoll() была добавлена в PHP 4.0.5, но под Windows не была включена до версии 4.2.3.
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.