【问题标题】:How to check if two strings contain the same letters?如何检查两个字符串是否包含相同的字母?
【发布时间】:2011-07-24 15:54:05
【问题描述】:
$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 声明?

【问题讨论】:

  • 您想知道两个字符串是否包含相同的字符,以相同的顺序(字符串相同),或者您想知道一个字符串中的任何字符是否在另一个字符串中?您可以显示您提供的字符串的预期结果吗?
  • 我想知道一个字符串中的所有字符是否都在另一个字符串中
  • taptapp 怎么样 - 你希望结果是什么?

标签: php string match


【解决方案1】:

考虑到以下两个变量,我想一个解决方案可能是:

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


并在你的两个 words 上调用该函数:

compare("pate", "tape");
compare("pate", "tapp");

会得到以下结果:

aept == aept
aept != appt

【讨论】:

  • 谢谢;很高兴我能帮忙:-)
  • 什么鬼? === 和你的有什么区别?
  • @genesis 'ab''ba' 包含相同的字母,所以我的 compare() 函数说它们是相同的。另一方面,'ab''ba' 不相等,所以var_dump("ab" === "ba"); 会得到你boolean false
  • +1 不错的解决方案。 str_split($string,1) 可能是preg_split 的一个很好的替代品。
  • @Mike 真丢脸,我完全忘记了这个功能;感谢您的评论,我将编辑我的答案以指出 str_split 可用于:-)
【解决方案2】:

使用===!==

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    • 2018-05-30
    • 2012-11-16
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多