Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 34 / 68

Building a Caesar Cipher (a Character-Shifting Cipher)

In this lesson you will implement the classic Caesar cipher and practise string manipulation using character codes. This is for anyone searching for "PHP encryption implementation".

The Caesar cipher is a simple cipher from ancient Rome that replaces each letter with the one a fixed number of positions further along the alphabet. It is the same idea as a childhood game of shifting every letter by three. It is very simple next to modern cryptography, but it is an ideal exercise for practising character-code arithmetic.

The sample code uses preg_replace_callback(), which processes only the parts matching a pattern through a callback. The key flow is converting a character to a number (its character code) with ord(), doing the arithmetic, and converting back with chr().

A common stumbling block for beginners is needing use ($shift) to reach the outer variable from inside preg_replace_callback(). That use keyword is essential whenever an anonymous function needs a variable from the enclosing scope.

Notice how anything that is not a letter is passed through unchanged. As a doorway into modern cryptography, it is worth building the mechanism yourself.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)