How do You Check if a String is a Palindrome in PHP?

Hello Friends Today, through this tutorial, I will tell you How do You Check if a String is a Palindrome in PHP With example? To check if a string is a palindrome in PHP, you can compare the string with its reverse. If both are the same, then the string is a palindrome. Here’s an example:

<?php
function isPalindrome($str) {
// Remove non-alphanumeric characters and convert to lowercase
$cleanedStr = preg_replace('/[^a-z0-9]/i', '', strtolower($str)); 
// Reverse the string
$reversedStr = strrev($cleanedStr);
// Compare the original and reversed strings
return $cleanedStr === $reversedStr;
}
// Test the function
$string1 = "A man, a plan, a canal, Panama";
$string2 = "racecar";
$string3 = "hello";
echo "'$string1' is a palindrome? " . (isPalindrome($string1) ? "Yes" : "No") . "<br>";
echo "'$string2' is a palindrome? " . (isPalindrome($string2) ? "Yes" : "No") . "<br>";
echo "'$string3' is a palindrome? " . (isPalindrome($string3) ? "Yes" : "No") . "<br>";
?>

Output:

'A man, a plan, a canal, Panama' is a palindrome? Yes
'racecar' is a palindrome? Yes
'hello' is a palindrome? No

In this example, the `isPalindrome()` function takes a string as input. It first removes non-alphanumeric characters and converts the string to lowercase using regular expressions and `strtolower()`. Then, it reverses the string using `strrev()`. Finally, it compares the original cleaned string with the reversed string and returns `true` if they are the same, indicating that the input string is a palindrome.