2011-07-24 118 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"; 
} 
相關問題