Skip to content

Instantly share code, notes, and snippets.

@roniemicro
Last active December 16, 2015 11:28
Show Gist options
  • Save roniemicro/5427042 to your computer and use it in GitHub Desktop.
Save roniemicro/5427042 to your computer and use it in GitHub Desktop.
Simple Palindrome Finder
<?php
function pushPalindrome(&$found, $word){
$str = strtolower($word);
if(strrev($str) === $str){
$found[strtolower($str)] = $word;
}
}
function findPalindrome($str, &$found = array(), $minimumLength = 1){
$length = strlen($str);
if($length < $minimumLength){
return count($found);
}
if($length <= $minimumLength){
pushPalindrome($found, $str);
return count($found);
}
for($i = $minimumLength; $i <= $length ; $i++){
pushPalindrome($found, substr($str, 0, $i));
}
return findPalindrome(substr($str,1), $found, $minimumLength);
}
function printPalindrome($str, $minimumLength = 1){
$result = array();
$palindromeFound = findPalindrome(str_replace(" ", "", $str), $result, $minimumLength);
if($palindromeFound == 0){
printf('The Word "%s" contains no palindromes' , $str);
}else{
printf('The Word "%s" contains %d palindromes:' , $str, $palindromeFound);
foreach($result as $palindromeWord){
echo nl2br(PHP_EOL . $palindromeWord);
}
}
}
printPalindrome("madam");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment