How to check if two strings contain the same letters?

拈花ヽ惹草 提交于 2020-01-11 06:25:29

问题


$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?


回答1:


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 :

sort($arr1);
sort($arr2);


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 {
    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



回答2:


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";
}


来源:https://stackoverflow.com/questions/6807864/how-to-check-if-two-strings-contain-the-same-letters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!