Skip to content

Instantly share code, notes, and snippets.

@basvandorst
Created December 12, 2011 19:02
Show Gist options
  • Select an option

  • Save basvandorst/1468595 to your computer and use it in GitHub Desktop.

Select an option

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++;
}
}
?>
@battirunner

Copy link
Copy Markdown

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