In this tutorial I’m going to show you how to find a word or a sentence is a Palindrome in PHP.
You may find scripts online but most of them are difficult to understand and almost all of them used loops to find it, but this php script I have written is very simple and not used any loops.
Let’s see the script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<html> <body> <h3>Find Palindrome or Not in PHP</h3> <form action="" method="post"> <label>Enter a word or a sentence<label> <input type="text" name="string" /> <input type="submit value="Submit" /> </form> </body> </html> <?php if($_POST){ $string = $_POST['string']; //remove all spaces $string = str_replace(' ', '', $string); //remove special characters $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); //change case to lower $string = strtolower($string); //reverse the string $reverse = strrev($string); if($string == $reverse){ echo "<p>It is Palindrome</p>"; }else{ echo "</p>Not Palindrome</p>"; } } ?> |
Read the comments in the script to understand what is happening.
Few palindrome words and sentences to check:
1. madam
2. civic
3. Madam, I’m Adam
4. A man, a plan, a canal: Panama.
5. No lemon, no melon.
The basic concept is reversing the entered string and comparing the string with the original string using (==) comparison operator. if both the original string and reversed string matched, then it is a Palindrome.
See the demo in here:
Really simple program ..Now i understand the concept..Thanks
Can you more explain preg_replace() function with detail.
thanks for your code
double quotes is missing for subit pls do have a look at it
thanx
Hi to every one, the contents existing at this web page are truly remarkable for people knowledge, well, keep up the nice work fellows.