Standard Palindrome in PHP

A palindrome is a word or phrase that reads the same forwards and backwards, ignoring spaces and punctuation. “Racecar”, “level”, and “A man a plan a canal Panama” are all palindromes.

Here’s a PHP script that checks whether a string is a standard palindrome by stripping non-alphanumeric characters, lowercasing, and comparing the result against its reverse.

The PHP Code

Replace $originalPalindromeToTest with the string you want to check:

<?php
$originalPalindromeToTest = "Madam I'm Adam";
$palindrome = strtolower(preg_replace("([^A-Za-z0-9])", "", $originalPalindromeToTest ));
$palindromeReversed = strtolower(strrev($palindrome));
echo "Original Statement: $originalPalindromeToTest <br /><br />";

if ($palindrome == $palindromeReversed){
echo "$palindrome is a Standard Palindrome of $palindromeReversed";
}else{
echo "$palindrome is <strong>not</strong> a Standard Palindrome of $palindromeReversed";
};
?>

How It Works

The script runs three operations on the input before comparing:

  • Strip non-alphanumeric characters: preg_replace removes anything that isn’t a letter or number (spaces, apostrophes, punctuation, etc.). “Madam I’m Adam” becomes “MadamImAdam”.
  • Lowercase: strtolower converts the cleaned string so the comparison is case-insensitive. “MadamImAdam” becomes “madamimadam”.
  • Reverse: strrev reverses the cleaned string. “madamimadam” reversed is still “madamimadam”.

If the cleaned string matches its reverse, it’s a palindrome. The if statement prints the result either way.

Example Output

Running the script with “Madam I’m Adam” prints:

Original Statement: Madam I'm Adam

madamimadam is a Standard Palindrome of madamimadam

With a non-palindrome like “hello”:

Original Statement: hello

hello is not a Standard Palindrome of olleh

Reusable Function Version

If you need to check multiple strings, wrapping the logic in a function is cleaner and easier to reuse across your codebase:

<?php
function isPalindrome(string $str): bool {
    $cleaned = strtolower(preg_replace('/[^A-Za-z0-9]/', '', $str));
    return $cleaned === strrev($cleaned);
}

var_dump(isPalindrome("racecar"));                      // bool(true)
var_dump(isPalindrome("Madam I'm Adam"));               // bool(true)
var_dump(isPalindrome("hello"));                        // bool(false)
var_dump(isPalindrome("A man a plan a canal Panama"));  // bool(true)
?>

This version uses === for strict comparison and standard forward-slash regex delimiters. It returns a boolean you can drop directly into any conditional.

If you’re working with PHP strings more broadly, limiting text length in PHP is another handy snippet for string handling.

1 thought on “Standard Palindrome in PHP”

  1. You should work on clean code. If you have palindrome2, the other variable should be palindrome1.

    Also, use white space. Indenting is good too for legibility.

    Reply

Leave a Comment