Created
February 22, 2017 11:52
-
-
Save deividaspetraitis/576ae2b92c5fb6580493871b75647a67 to your computer and use it in GitHub Desktop.
Returns TRUE if the two input strings form anagrams of each other otherwise FALSE
This file contains hidden or 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 | |
$string1 = strtolower(preg_replace('/\s+/', '', "AstroNomers")); // Prepare string | |
$string2 = strtolower(preg_replace('/\s+/', '', "no more stars")); // Prepare string | |
$bool = isAnagram ( $string1, $string2 ); | |
/** | |
* Returns TRUE if the two input strings form anagrams of each other otherwise FALSE. | |
* Also return FALSE in case of invalid inputs. | |
* | |
* @param $string1 | |
* @param $string2 | |
* | |
* @return bool | |
*/ | |
function isAnagram($string1, $string2) | |
{ | |
if (!is_string($string1) || !is_string($string2)) { | |
return false; | |
} | |
$str = str_split($string2); | |
$key = array_search($string1[0], $str); | |
if ($key !== false) { | |
unset($str[$key]); | |
} | |
$string1 = substr($string1, 1); | |
$string2 = !empty($str) ? implode("", $str) : false; | |
if ($string1 != false && $string2 != false) { | |
return isAnagram($string1, $string2); | |
} | |
return $string1 == false && $string2 == false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment