2011-07-24 119 views
3
$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

你想知道,如果两个字符串包含相同的字符,以相同的顺序(字符串是相同的),或者你想知道,如果从一个字符串中的任何字符是另一个字符串?你能显示你提供的字符串的预期结果吗? – Mike

+0

我想知道一个字符串中的所有字符是否在另一个字符串中 – faq

+0

'tap'和'tapp'如何?您期望的结果是什么? – Mike

回答

9

我想一个解决办法是,考虑到以下两个变量:

$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); 


之后,破灭的阵列,打造所有的字母按字母顺序排列:

$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 
+0

非常好,谢谢! ill accec it – faq

+0

谢谢;很高兴我可以帮助:-) –

+0

什么地狱? ===和你的有什么区别? – genesis

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"; 
} 
相关问题