Last active
December 16, 2015 14:29
-
-
Save iamshanto/5449039 to your computer and use it in GitHub Desktop.
Find Palindrom from string
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 printPalindromes($str) | |
{ | |
#$str = strtolower(preg_replace("'\s+'", '', $str)); | |
$str = strtolower(preg_replace("([^A-Za-z0-9])", "", $str)); | |
$length = strlen($str); | |
$reverse = strrev($str); | |
$matches = array(); | |
$palindrom = $str; | |
// Check for character matching from reverse position | |
for ($i = 0; $i < ($length / 2); $i++) { | |
if ($str[$i] == $str[($length - $i - 1)]) { | |
$matches[] = $str[$i]; | |
} | |
} | |
// Check for word matching | |
for ($i = 0; $i < ($length / 2); $i++) { | |
if( $str == $reverse){ | |
$matches[] = $str; | |
$str = substr($str, 1, -1); | |
$reverse = substr($reverse, 1, -1); | |
} | |
} | |
$matches = array_unique($matches); | |
$found = count($matches); | |
if ($found == 0) { | |
echo 'No Palindrom found'; | |
} else { | |
echo 'The Word "'.$palindrom.'" contains '.$found.' palindromes:' . '<br>'; | |
foreach ($matches as $key => $match) { | |
echo $match . '<br>'; | |
} | |
} | |
} | |
printPalindromes('madam'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment