$a === $b TRUE if $a is equal to $b, and they are of the same type.
Источник
How to check if two strings contain the same letters?
Do you want to know if two strings contain the same characters, in the same order (the strings are the same), or do you want to know if any character from one string is in the other string? Can you show the expected result for the strings you have provided?
2 Answers 2
I suppose a solution could be to, considering the two following variables :
$textone = "pate"; $texttwo = "tape";
1. First, split the strings, to get two arrays of letters :
$arr1 = preg_split('//', $textone, -1, PREG_SPLIT_NO_EMPTY); $arr2 = preg_split('//', $texttwo, -1, PREG_SPLIT_NO_EMPTY);
Note that, as pointed out by @Mike in his comment, instead of using preg_split() like I first did, for such a situation, one would be better off using str_split() :
$arr1 = str_split($textone); $arr2 = str_split($texttwo);
2. Then, sort those array, so the letters are in alphabetical order :
3. After that, implode the arrays, to create words where all letters are in alphabetical order :
$text1Sorted = implode('', $arr1); $text2Sorted = implode('', $arr2);
4. And, finally, compare those two words :
if ($text1Sorted == $text2Sorted) < echo "$text1Sorted == $text2Sorted"; >else
Turning this idea into a comparison function would give you the following portion of code :
function compare($textone, $texttwo) < $arr1 = str_split($textone); $arr2 = str_split($texttwo); sort($arr1); sort($arr2); $text1Sorted = implode('', $arr1); $text2Sorted = implode('', $arr2); if ($text1Sorted == $text2Sorted) < echo "$text1Sorted == $text2Sorted
"; > else < echo "$text1Sorted != $text2Sorted
"; > >
And calling that function on your two words :
compare("pate", "tape"); compare("pate", "tapp");
Would get you the following result :
Источник
Строковые функции в PHP. Сравнение строк в PHP
В PHP для сравнения строк используется несколько функций. В этой статье мы поговорим о том, как сравнить строки в PHP.
Итак, для сравнения можно использовать: — strcmp(); — strncmp(); — strcasecmp(); — strncasecmp(); — strnatcmp(); — strnatcasecmp(); — similar_text(); — levenshtein().
1. strcmp()
int strcmp(string str1, string str2)
Данная функция сравнивает 2 строки в PHP и возвращает: — 1, когда строка str1 лексикографически больше, чем str2; — 0, когда строки полностью совпадают; — 1, когда строка str1 лексикографически меньше str2.
Функция чувствительна к регистру, поэтому регистр оказывает влияние на результат сравнений (сравнение выполняется побайтово).
Пример работы strcmp() в PHP:
"); echo("Result of strcmp ($str2, $str1)> is "); echo(strcmp ($str2, $str1)); echo("
"); echo("Result of strcmp ($str1 , $str1) is "); echo(strcmp ($str1,$str1)); ?>
Result of strcmp (ttt , tttttttttt) is -1 Result of strcmp (tttttttttt, ttt) is 1 Result of strcmp (ttt, ttt) is 0
2. strncmp()
int strncmp(string str1, string str2, int len)
Данная функция отличается от strcmp() прежде всего тем, что сравнивает первые len байтов, т. е. начала строк. А когда len меньше длины наименьшей из строк, строки сравниваются целиком.
Что касается остального, то всё аналогично strcmp() , включая чувствительность к регистру.
3. strcasecmp()
int strcasecmp(string str1, string str2)
И эта функция сравнения работает так же, как и strcmp() . Разница лишь в том, что не учитывается регистр букв.
4. strncasecmp()
int strncasecmp(string str1, string str2, int len)
strncasecmp() сравнивает начала строк, не учитывая регистр.
5. strnatcmp()
int strnatcmp(string str1, string str2)
Выполняет «естественное» сравнение строк в 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.
"); usort ($array1, strcmp); print_r ($array1); echo ("
"); echo("естественная сортировка:"); echo("
"); usort ($array2, strnatcmp); print_r ($array2); ?>
стандартная сортировка: Array([0]=>pict1.gif [1]=> pict10.gif [2]=>pict2.gif [3]pict20.gif) естественная сортировка: Array([0]=>pict1.gif [1]=> pict2.gif [2]=>pict10.gif [3]pict20.gif)
6. strnatcasecmp()
int strnatcasecmp(string str1, string str2)
Выполняет вышеупомянутое «естественное» сравнение строк, но уже не учитывая регистр.
7. similar_text()
int similar_text(string str_first, string str_second [, double percent])
Определяет схожесть двух строк по алгоритму Оливера. Возвращается число символов, совпавших в строках str_second и str_first. Третий параметр необязателен — он передаётся по ссылке, плюс в нём сохраняется совпадение строк в процентах.
"); echo("$var"); echo("
"); echo("и в процентах:"); echo("
"); echo($tmp); // для вывода информации в % происходит обращение к $tmp ?>
Результат выполнения функции similar_text() для строк Hello, world! и Hello! в числе символов: 6 и в %: 63.157894736842
8. levenshtein()
Определяет различие Левенштейна при сравнении двух строк в PHP.
int levenshtein(string str1, string str2) int levenshtein(string str1, string str2, int cost_ins, int cost_rep, int cost_del) int levenshtein(string str1, string str2, function cost)
Различие Левенштейна — минимальное количество символов, которое нужно заменить, удалить или вставить, чтобы превратить строку str1 в str2.
Сложность алгоритма — O(m*n), поэтому функция levenshtein() в PHP работает быстрее, чем similar_text() . Обратите внимание, что у функции 3 вида синтаксиса.
Хотите знать больше? Записывайтесь на курс "Backend-разработчик на PHP"!
Источник
string matching via if statement PHP
This is then put through an if statement to check whether or not its the letter a. If it is then echo - you wrote the letter a, else - you did not write the letter a.
It does work, but in the wrong way. Every letter I type in comes as 'You wrote a'. I only want it to echo this if the user typed a. Otherwise, echo 'You did not write a' . EDIT: When I try == instead of = it says 'You did not write a' for everything. Even when I type a. EDIT 2: When I try the string compare parameter, It didnt work. Any suggestions where I am going wrong? FULL SCRIPTS OF BOTH PAGES: index.php
They all are telling you that you are assigning the letter "a" to the variable $input. To compare the two, you must use ==. Close your eyes and accept an answer 🙂
Okay, can you post the full code of the first page, and the second page? Just so's I can try this for myself?
Are you really only typing a single a into a textarea? What is it you actually want to compare against - presence of an a at the start of the string maybe?
4 Answers 4
== is the conditional for comparison. = is the assignment operator.
You might want to use strcmp as it is binary-safe.
EDIT: Taking another stab here - in your code as posted (I copy pasted it) you have whitespace in your textarea by default.
Don't put a line break between the and tags. This adds whitespace to the start of 'a'.
Removing this made it work properly in my test.
EDIT: As per the accepted answer and reposted code, trim() is in fact the proper function to remove all leading and trailing whitespace.
@Ryan Murphy This must be something further down the stack. Can you post the code of your form? Perhaps it's enctype is wrong? Both these comparisons should work if the incoming data is a string and only contains 'a'.
Thank you for adding the remaining code. Could you run print_r($_POST); in the responding page and post its contents as well?
@Ryan Murphy - Edited for another possible reason - extra whitespace in your textarea tag the 'a' gets appended to. Let me know if this works.
Your problem is a confusion between the = and == operators.
If you want to compare two values in PHP, you must use == (that is, two equal signs together).
Using a single equal sign on its own will set the value on the right to the value on the left (as per its use in the first line of your code example).
Note, there is also a tripple-equal operator === , which is also used for comparison, where you want to also compare the data type of the two sides. For basic use, the double equal is usually sufficient, but the manual page will give you more info on the difference between the two.
Re your edit - All the comments suggesting == instead of = are right. The single-equal operator is the wrong thing to use. If you're still getting a problem with the double-equal operator, then $input doesn't actually equal a .
In this case, you may need to debug your input. Assuming your echo $input; line does show a , I'd say the most likely scenario is that you're entering some white space with it, maybe a carriage return or something like that.
To prove that, you may want to print it like this:
That will show up any unexpected extra characters you may have entered.
If you're not worried about white space, then use the trim() function to get rid of it.
You could also use functions like strlen() to check how long the string is, etc.
Okay, looking at your HTML code, I'd say it's definitely going to be the white space issue.
This will result in the textarea being created with a line feed as it's default content, because the opening and closing tags are on separate lines. If you just type a into it, what you'll actually submit will be a plus a line feed.
The best advice is probably to trim() the input before you check it.
Источник