<?php
function isPalindrome(string &$str): bool
{
$regex = <<<REGEX
/
^ #start of string
( #start capture group 1
( #start capture group 2
. #match any non-newline character
) #end capture group2
(?1) #repeat the expression of capture group 1
\2 #match the character from capture group 2
| #or
.? #the middle character (if odd length input string) or no character (if even length input string)
) #end capture group 1
$ #end of string
/x
REGEX;
return (bool) preg_match($regex, $str);
}
function sanitizePalindrome(&$str)
{
return preg_replace('/[^a-z]+/', '', strtolower($str));
}
$tests = [
'',
'radar',
'f',
'neveroddoreven',
'foo',
'palindrome',
'Red rum, sir, is murder'
];
foreach ($tests as $test) {
$test = sanitizePalindrome($test); // this is optional
printf("%20s : %s\n", $test, json_encode(isPalindrome($test)));
}