Skip to content

Instantly share code, notes, and snippets.

@basvandorst
Created December 12, 2011 19:02
Show Gist options
  • Save basvandorst/1468595 to your computer and use it in GitHub Desktop.
Save basvandorst/1468595 to your computer and use it in GitHub Desktop.
PHP: Find longest palindrome
<?php
/**
* Easy way to find the longest palindrome in a string
*
* Solution for: http://challenge.greplin.com/
* The Greplin Programming Challenge: Version 1
*
* @author Bas van Dorst <info@basvandorst.nl>
*/
$data = "FourscoreracecarsthatandsevenyearsagoourfaathersbroughtforthonthiscontainentanewnationconceivedinzLibertyanddedicatedtothepropositionthatallmenarecreatedequalNowweareengagedinagreahtcivilwartestingwhetherthatnaptionoranynartionsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplaceforthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproperthatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannothallowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfaraboveourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayherebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretotheulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforustobeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionthatweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsderGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeopleshallnotperishfromtheearth";
for($i=0; $i<strlen($data); $i++ )
{
$palindrome = true;
$offset = 1;
while($palindrome)
{
$word = substr($data, $i-$offset, ($offset*2)+1 );
if( $word == strrev($word) ) {
print strlen($word) .' '. $word.'<br />';
} else {
$palindrome = false;
}
$offset++;
}
}
?>
@ammar-hayder
Copy link

Got bug to apply on 'BBBBBBB';

@takalot
Copy link

takalot commented Nov 6, 2017

Hello. is it possible to help this php function in hebrew?

@battirunner
Copy link

It is not working for simple input like "abba" or "abbac"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment