PHP - Check if a string is a rotation of another string

Viewed 1848

Need to write a code block which check is one string is a rotation of another.

Looked at loads of posts on here and it is all in Java or C++ but I need to do it in PHP.

I have tried a few different things, trying to work from the C++ and Java examples but I am not having any luck, here is my current code:

<?php

function isSubstring($s1, $s2) {


    if(strlen($s1) != strlen($s2)) {
        return false;
    }

    if(WHAT TO PUT HERE) {
        echo "it is!";
    } else {
        echo "nope";
    }
}


isSubstring("hello", "helol");

?>
7 Answers

Here is a multibyte safe function to compare the two strings:

function mb_isAnagram($s1, $s2) {
    if (strlen($s1) != strlen($s2)) {
        return false;
    } else {
        $c1 = preg_split('//u', $s1, null, PREG_SPLIT_NO_EMPTY);
        $c2 = preg_split('//u', $s2, null, PREG_SPLIT_NO_EMPTY);
        sort($c1);
        sort($c2);
        if ($c1 === $c2) {
            return true;
        } else {
            return false;
        }
    }
}

This is the function for string rotation.

echo isRotationalString("abcdef","efabcd")?'It is':'It is not';

function isRotationalString($str1,$str2){
    $len = strlen($str1); 
    if($str1 === $str2){
        return true;
    } else {
        if($len == strlen($str2)) {
    
            $stringMatchedArr1 = $stringMatchedArr2 = [];
            for($i=0; $i<$len; $i++) {
                $substr = substr($str1,$i );
                $pos = strpos($str2, $substr);
                if($pos !== false) {
                    $stringMatchedArr1[] = $substr;
                }
            }
        
            for($j=1; $j <= $len; $j++) {
                $substr = substr($str1, 0, $j );
                $pos = strpos($str2, $substr);
                if($pos !== false) {
                    $stringMatchedArr2[] = $substr;
                }
            }
        
            foreach($stringMatchedArr2 as  $string1) {
                foreach($stringMatchedArr1 as $string2) {
                    if($string1.$string2 == $str1)
                         return true;
                }
            }
       
        }
    }
}
Related