[英]How to check if two strings contain the same letters?
$textone = "pate"; //$_GET
$texttwo = "tape";
$texttre = "tapp";
if ($textone ??? $texttwo) {
echo "The two strings contain the same letters";
}
if ($textone ??? $texttre) {
echo "The two strings NOT contain the same letters";
}
What if
statement am I looking for? if
我要找的话怎么办?
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 : 1.首先,拆分字符串,得到两个字母数组:
$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()
: 请注意,正如@Mike在他的评论中所指出的,不是像我第一次那样使用
preg_split()
,对于这种情况,最好使用str_split()
:
$arr1 = str_split($textone);
$arr2 = str_split($texttwo);
2. Then, sort those array, so the letters are in alphabetical order : 2.然后,对这些数组进行排序,因此字母按字母顺序排列:
sort($arr1);
sort($arr2);
3. After that, implode the arrays, to create words where all letters are in alphabetical order : 3.在此之后,破灭的阵列,要创造一个所有的字母按字母顺序排列的话 :
$text1Sorted = implode('', $arr1);
$text2Sorted = implode('', $arr2);
4. And, finally, compare those two words : 4.最后,比较这两个词 :
if ($text1Sorted == $text2Sorted) {
echo "$text1Sorted == $text2Sorted";
}
else {
echo "$text1Sorted != $text2Sorted";
}
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<br />";
}
else {
echo "$text1Sorted != $text2Sorted<br />";
}
}
And calling that function on your two words : 并在你的两个单词上调用该函数:
compare("pate", "tape");
compare("pate", "tapp");
Would get you the following result : 会得到以下结果:
aept == aept
aept != appt
use ===
and !==
使用
===
和!==
if ($textone === $texttwo) {
echo "The two strings contain the same letters";
}else{
echo "The two strings NOT contain the same letters";
}
or 要么
if ($textone === $texttwo) {
echo "The two strings contain the same letters";
}
if ($textone !== $texttwo) {
echo "The two strings NOT contain the same letters";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.