$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";
}
我在寻找什么if
声明?
答案 0 :(得分:11)
考虑到以下两个变量,我想一个解决方案可能是:
$textone = "pate";
$texttwo = "tape";
1。首先,拆分字符串,得到两个字母数组:
$arr1 = preg_split('//', $textone, -1, PREG_SPLIT_NO_EMPTY);
$arr2 = preg_split('//', $texttwo, -1, PREG_SPLIT_NO_EMPTY);
请注意,正如@Mike在评论中指出的那样,不是像我之前那样使用preg_split()
,对于这种情况,最好使用str_split()
:
$arr1 = str_split($textone);
$arr2 = str_split($texttwo);
2. 然后,对这些数组进行排序,因此字母按字母顺序排列:
sort($arr1);
sort($arr2);
3. 之后,内爆数组,创建单词,其中所有字母都按字母顺序排列:
$text1Sorted = implode('', $arr1);
$text2Sorted = implode('', $arr2);
4. 最后,比较这两个字:
if ($text1Sorted == $text2Sorted) {
echo "$text1Sorted == $text2Sorted";
}
else {
echo "$text1Sorted != $text2Sorted";
}
将这个想法变成比较函数会给你以下部分代码:
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 />";
}
}
并在您的两个单词上调用该函数:
compare("pate", "tape");
compare("pate", "tapp");
会得到以下结果:
aept == aept
aept != appt
答案 1 :(得分:0)
使用===
和!==
if ($textone === $texttwo) {
echo "The two strings contain the same letters";
}else{
echo "The two strings NOT contain the same letters";
}
或
if ($textone === $texttwo) {
echo "The two strings contain the same letters";
}
if ($textone !== $texttwo) {
echo "The two strings NOT contain the same letters";
}