Skip to content

Instantly share code, notes, and snippets.

@deividaspetraitis
Created February 22, 2017 11:52
Show Gist options
  • Save deividaspetraitis/576ae2b92c5fb6580493871b75647a67 to your computer and use it in GitHub Desktop.
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
<?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