Last active
December 16, 2015 11:28
-
-
Save roniemicro/5427042 to your computer and use it in GitHub Desktop.
Simple Palindrome Finder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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