What is the str_rot13 function in PHP?

In PHP, we can perform an ROT13 transformation of a string using the str_rot13 function.

ROT13 is an algorithm that replaces a letter with the 13th letter after it in the alphabet.
Do not use this as an encryption algorithm.

%0 node_1 Hello, Educative! node_3 Uryyb, Rqhpngvir! node_1->node_3
A visual representation of the ROT13 cipher

Syntax

str_rot13(string $string): string

Parameters

This function requires the string we want to encode as a mandatory parameter.

Return value

The str_rot13function will return the computed ROT13 of the given string.

This function works as both a decoder and an encoder.

This function will only encode the alphabet characters; it leaves all other characters untouched.

Code

In this example, we will encode the string and then decode it back to the original version.

<?php
$mystr = "Hello, Educative!";
$mystr = str_rot13($mystr);
echo "First encode: " . $mystr . "\n"; // note that the "!" is untouched!
$mystr = str_rot13($mystr);
echo "Second encode: " . $mystr;

Explanation

  • In line 2, the input string is declared.
  • In line 3, the str_rot13 function is applied to the input string.
  • In line 4, the encoded string is printed.
  • In line 5, the str_rot13 function is applied to the encoded string to be decoded.
  • In line 6, the original string obtained through decoding the encoded string is printed.