2014-01-23 17 views
3

我正在製作一個非常簡單的解密腳本,我可以解決一個問題。如何替換PHP中的確切內容

<?PHP 

// Define arrays 
$search = array("3", "4", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "1", "2"); 
$replace = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"); 

$display = "Please Enter Encrypted Message!"; 

if ($_POST['submit'] == "Submit") 
{ 
    // Get post data 
    $subject = $_POST['encrypted']; 


    $result = str_replace($search, $replace, $subject); 

    $display = "Decrypted Message: {$result}"; 
} 
?> 
<html> 
    <head> 
    <title>Encryption</title> 
    </head> 
    <body> 
     <form method="post" action="encryption.php"> 
      <input type="text" name="encrypted" /><br /> 
      <input type="submit" name="submit" value="Submit" /> 
     </form> 
     <?PHP echo $display; ?> 
    </body> 
</html> 

如果我進入到 '' 將返回 'Y d YD' 在我的意圖是有 'Y d N' 返回 '1 7 17'。

我的問題是,它將用'D'替換'1'和'7'中的所有'1',但不會將'1'和'7'一起檢測爲'17'並將其替換爲' N」。

有沒有人有任何想法來檢測確切的字符串/ int? 如果任何人在輸入加密數據(例如,1 7 17或1,7,17​​)時都有很好的分離技術。

在此先感謝!

+0

不理想,但快速的解決方案 - 請嘗試重新排序的搜索和替換字符,以便他們在尺寸相反的順序 - 這樣,你永遠不會遇到這個問題。 –

+0

作爲替代方案。不要試圖在一個單獨的'str_replace'中執行它,請循環輸入字符串並逐個查找替換字符,一次構建一個新字符串。 –

+0

@ user3228721如果您有答案,請將其標記爲正確。 – Styphon

回答

1

你可能會更好地循環你從$ _POST輸入的值,並將它們匹配到你的數組值。像這樣的東西會工作:

// Use $search as the array key and $replace as the value 
$combi = array_combine($search, $replace); 

$display = "Please Enter Encrypted Message!"; 

if ($_POST['submit'] == "Submit") 
{ 
    // Get post data 
    $subject = $_POST['encrypted']; 

    // Split our post data into an array 
    $chars = explode(' ', $subject); 

    // Loop over each character entered and get 
    // the corresponding value back from our combi array 
    foreach($chars as $char) { 
     $result .= $combi[$char]; 
    } 

    $display = "Decrypted Message: {$result}"; 
} 

如果你不需要讓你的陣列分離爲別的,你可能只是自己將它們組合起來,取下array_combine。也許值得在foreach中進行檢查,以確保每個$ _POST值($ char)存在於$ combi數組中 - if(array_key_exists($ char,$ combi))或類似。希望有所幫助。

參考:explodearray_key_existsarray_combine

+0

感謝您的幫助,我會盡全力給他們回覆。 – Rubixryan

+0

謝謝,您的代碼工作得很好,再次感謝,我一定會問你們未來! – Rubixryan

3

嘗試重新排序您的$ search和$ replace,以便更大的數字是第一個。在替換1和7之前,您需要替換17。這樣,在任何Y或D之前,腳本中的任何N都將被替換。