Palindrome Checker
Write a PHP function that checks if a string is a palindrome — it reads the same forwards and backwards. Ignore case and non-alphanumeric characters.
Convert the string to lowercase with strtolower(). Remove all non-alphanumeric characters using preg_replace('/[^a-z0-9]/', '', $clean). The cleaned string contains only letters and digits in lowercase. Compare this cleaned string with its reverse using strrev().
An alternative two-pointer approach: set $left = 0 and $right = strlen($s) - 1. While $left < $right, compare characters at both positions. If they differ, return false. If they match, move $left up by 1 and $right down by 1.
Edge cases include empty strings (true), single characters (true), strings with only non-alphanumeric characters (true after cleaning), and mixed case like 'RaceCar'.
Time complexity is O(n). Space complexity is O(n) for the cleaned string copy.
The two-pointer approach uses O(1) extra space and avoids creating intermediate strings, making it memory-efficient for long strings. The ctype_alnum() function checks if a character is alphanumeric. The two-pointer approach with ctype_alnum() and strtolower() handles all ASCII palindromes correctly without relying on regex functions that may have platform-dependent behavior.Example Input & Output
Algorithm Flow

Solution Approach
Write a PHP function that checks if a string is a palindrome — it reads the same forwards and backwards. Ignore case and non-alphanumeric characters.
Convert the string to lowercase with strtolower(). Remove all non-alphanumeric characters using preg_replace('/[^a-z0-9]/', '', $clean). The cleaned string contains only letters and digits in lowercase. Compare this cleaned string with its reverse using strrev().
An alternative two-pointer approach: set $left = 0 and $right = strlen($s) - 1. While $left < $right, compare characters at both positions. If they differ, return false. If they match, move $left up by 1 and $right down by 1.
Edge cases include empty strings (true), single characters (true), strings with only non-alphanumeric characters (true after cleaning), and mixed case like 'RaceCar'.
Time complexity is O(n). Space complexity is O(n) for the cleaned string copy.
Best Answers
<?php
function isPalindrome($text) {
$left = 0;
$right = strlen($text) - 1;
while ($left < $right) {
while ($left < $right && !ctype_alnum($text[$left])) $left++;
while ($left < $right && !ctype_alnum($text[$right])) $right--;
if (strtolower($text[$left]) !== strtolower($text[$right])) return false;
$left++;
$right--;
}
return true;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
