I wrote a Caesar cipher (a script where, given a message, the letters in the message are shifter x number of places; e.g. A => D, B => E, C => F, X => A, Y => B, Z => C, etc.). It works but it shifts all ASCII characters. I want to exclude characters that are not A-Z or a-z (outside the ASCII values of 65 - 90 and/or 97 - 122) so that spaces, punctuation, numbers all remain the same instead of shifting as well.

So very close! I changed $sp = $_POST['offset']; and $string to $_POST['msg']; as that's where the user-entered info comes from.

I entered "hi bill" into the form and on Encode it printed 3 different values: "lm fmpplm fmpp" into the textarea box, "Array" into the Encoded message output at the bottom, and "lm fmpp" where nothing should be printing. It looks like somehow it printed the decoded message twice (i.e. lm fmpp once and lm fmpp again[lm fmpplm fmpp]).

Remove the echo command at the end of the encode file, and in the main file, use $encstring, not $newstring. :)

In fact, the way you are modularizing things (which is good) could be taken a step further, and putting the encode/decode stuff into functions that return the resulting strings, which you then would call in the main file; or even (gasp!) a class definition with encode() and decode() methods. :)

02-02-2014, 12:04 AM

NogDog

In fact, here's how you might put it all into a single function, so that we can enforce the DRY (don't repeat yourself) principle:

How do I get it to work the other way around? I tried $i--, $ascii -= 1, and $ascii += 26 in various combinations. $ascii -= 1 seemed to work the closest, but for my test case, I typed "Hi, bob!" with an offset of 4, and the encode function worked perfectly. The first time I use Decode it works; it decodes "Lm, fsf!" back to "Hi, bob!". But if I hit Decode again, it prints "De, ^k^!".

When all this is said and done, I owe you a drink of your choice! ;)

02-02-2014, 11:53 AM

NogDog

You want to do $ascii -= 1 to decrement $ascii, but then you need to use += 26 if it goes below the minimum value. (You could use $ascii-- or even --$ascii, but for readability/maintainability reasons, I prefer to avoid those.)