Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace exact content in PHP

Tags:

php

I was making an extremely simple decryption script and I can across a problem.

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

If I enter '1 7 17' in to the '' it will return 'Y D YD' where my intention is to have 'Y D N' returned.

My problem is, it is replacing any '1's with 'Y' and all the '7's with 'D' but won't detect the '1' and '7' together as '17' and replace it with 'N'.

Has anyone got any ideas on getting to to detect the exact string/int? If anyone has got any good separation techniques when inputting the encrypted data (eg, 1 7 17 or 1, 7, 17) that would be great.

Thanks in advance!

like image 578
Rubixryan Avatar asked Sep 15 '26 15:09

Rubixryan


1 Answers

Try re-ordering your $search and $replace, so that the larger numbers are first. You need to replace 17 before you replace 1 and 7. That way any N's will be replaced in your script before any Y's or D's.

like image 156
Styphon Avatar answered Sep 17 '26 05:09

Styphon