PHP Strings Primer - Reversing strings
(Page 14 of 37 )
The 'strrev()' function accepts a string and returns that same string in reverse order. All capitalization and punctuation remain the same within the string. This function is regularly used in algorithms and can be applied in simple word games.
PalindromesA palindrome is a word that is spelled the same forward as backward. Using the 'strrev()' function, we can easily check to see if a word fits that condition. This example assumes that information is being posted to it from a HTML form.
<?php $word = strtolower ($_POST['userinput']); if ($word == strrev ($word)) { Â Â Â echo 'The word is a palindrome'; } else { Â Â Â echo 'This is not a palindrome'; } ?> |
Notice that we also used to 'strtolower()' function in this example. We are accepting user input, so it is always best to be sure that we place the data in a state that we can validate. If the user were to enter a word with the first letter capitalized, it would not pass the comparison without the use of the 'strtolower()' function, even if it actually were a palindrome.
The LUHN FormulaA very common use for the 'strrev()' function is within an algorithm to check the validity of credit card numbers. The algorithm is called the LUHN mod 10 formula. This algorithm does not ensure the credit card itself is valid, just the number. It will report as valid a number that matches the algorithm but as not yet been issued to anyone. This formula comes in handy as a first line check before sending information to a credit card merchant for processing.
The most common method for implementing the algorithm is to start by reversing the credit card number. Below is an implementation of the LUHN formula in PHP, using the 'strrev()' function. Several other string functions are used in this example, which we will cover at a later point.
<?php $ccnum = strrev($ccnum); $total = 0;
for ($x = 0; $x < strlen ($ccnum); $x++) { Â $digit = substr($ccnum,$x,1); Â if ($x % 2 == 0) { Â Â Â $digit *= 2; Â Â Â if (strlen ($digit) == 2) Â Â Â Â Â Â Â $digit = substr ($digit, 0, 1) + substr ($digit, 1, 1); Â } Â $total += $digit; }
if ($total % 10 == 0) print 'Good Credit Card Number'; ?> |
Next: Padding strings >>
More Programming Basics Articles
More By Matt Wade