determining if a word is a palindrome

Hi everyone I have to determine if a word is a palindrome and so far I have this code:

<?php $word=$_POST['word']; $reverse=strrev($word); if ($word == $reverse) echo 'This word is a palindrome'; else echo 'This is not a palindrome'; ?>

The only problem is I have to remove all spaces, apostrophes, commas, etcs.

For example I need the words Madam I’m Adam to come back as a palindrome.

I am not quite sure how to remove unwanted characters…I was told to use str_replace but I don’t know how to use that function. Any help would be great. Thanks

You can use str_replace to do that but you would need to list all the characters you don’t want and if you miss any they will get through.

Instead it would be better to replace anything that is not a character you want so if you only want letters and numbers you could do this:

<?php
$str = "Madam I'm Adam";

$new_str = preg_replace("/[^A-Za-z0-9]/", '', $str); // replace any charecter that is not A-Z a-z 0-9

if(strtolower($new_str) == strtolower(strrev($new_str))) // make both lower case and reverse one
	echo 'This is a palindrome';
else
	echo 'This is not a palindrome';
?>

thanks so much for your help…it worked!!

Sponsor our Newsletter | Privacy Policy | Terms of Service