Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,880 questions

51,806 answers

573 users

How to find longest palindrome substring in PHP

2 Answers

0 votes
function longestPalindromeSubstring($str) {
    $len = strlen($str);
    $longestLength = 1;
    $start = 0;
    
    for ($i = 0; $i < $len; $i++) {
        for ($j = $i; $j < $len; $j++) {
            $palindrome = 1;
            for ($k = 0; $k < (int)(($j - $i + 1) / 2); $k++) {
                if ($str[$i + $k] != $str[$j - $k]) {
                    $palindrome = 0;
                }
            }
            if ($palindrome != 0 && ($j - $i + 1) > $longestLength) {
                $start = $i;
                $longestLength = $j - $i + 1;
            }
        }
    }
    
    echo "Longest palindrome substring = ";
    for ($i = $start; $i <= $start + $longestLength - 1; $i++) {
        echo $str[$i];
    }
    echo "\n";
    
    return $longestLength;
}

$str = "qabcbaproggorpxyyxzv";

$result = longestPalindromeSubstring($str);

echo "Length palindrome substring length = " . $result;




/*
run:
  
Longest palindrome substring = proggorp
Length palindrome substring length = 8
  
*/

 



answered Jun 4, 2023 by avibootz
edited Jun 6, 2023 by avibootz
0 votes
function longestPalindromeSubstring(string $s): string {
    $start = 0;
    $end = 0;
    $length = strlen($s);

    for ($i = 0; $i < $length; $i++) {
        $len1 = expandFromCenter($s, $i, $i);       // Odd length
        $len2 = expandFromCenter($s, $i, $i + 1);   // Even length
        $len = max($len1, $len2);

        if ($len > ($end - $start)) {
            $start = $i - intdiv($len - 1, 2);
            $end = $i + intdiv($len, 2);
        }
    }

    return substr($s, $start, $end - $start + 1);
}

function expandFromCenter(string $s, int $left, int $right): int {
    while ($left >= 0 && $right < strlen($s) && $s[$left] === $s[$right]) {
        $left--;
        $right++;
    }
    
    return $right - $left - 1;
}

$str = "qabcbaproggorpxyyxzv";

$longestPalindrome = longestPalindromeSubstring($str);

echo "Longest palindrome substring = " . $longestPalindrome . "\n";
echo "Length palindrome substring length = " . strlen($longestPalindrome);



/*
run:

Longest palindrome substring = proggorp
Length palindrome substring length = 8

*/

 



answered Sep 27, 2025 by avibootz
...