🎉 I'm releasing 12 products in 12 months! If you love product, checkout my new blog workingoutloud.dev

Back to home

PHP Anagrams

    This expects an installation on the system of phpunit.

    Test File

    Create anagrams_test.php:

    <?php require "anagrams.php"; class AnagramsTest extends PHPUnit\Framework\TestCase { public function testAnagramsBasic() { $a = "tokyo"; $b = "kyoto"; $this->assertEquals(true, anagrams($a,$b)); } public function testAnagramsWithCapitals() { // $this->markTestSkipped('Skipped.'); $a = "Tokyo"; $b = "kyoto"; $this->assertEquals(true, anagrams($a,$b)); } public function testAnagramsWithPunctuation() { // $this->markTestSkipped('Skipped.'); $a = "To 35k 2@4yo"; $b = "kYoTo223!!"; $this->assertEquals(true, anagrams($a,$b)); } }


    Create anagrams.php:

    <?php function anagrams($a, $b) { $regA = preg_replace("/[^a-z]/i", "", $a); $regB = preg_replace("/[^a-z]/i", "", $b); $regA = strtolower($regA); $splitA = str_split($regA); sort($splitA); $regB = strtolower($regB); $splitB = str_split($regB); sort($splitB); $resA = implode("", $splitA); $resB = implode("", $splitB); return $resA == $resB; }

    Running Tests

    Change into directory and run phpunit.phar anagrams_test.php.

    Personal image

    Dennis O'Keeffe

    • Melbourne, Australia

    Hi, I am a professional Software Engineer. Formerly of Culture Amp, UsabilityHub, Present Company and NightGuru.
    I am currently working on Visibuild.


    Get fresh posts + news direct to your inbox.

    No spam. We only send you relevant content.

    PHP Anagrams


    Share this post