Find first character that is different between two strings

后端 未结 4 1171
心在旅途
心在旅途 2020-11-28 20:14

Given two equal-length strings, is there an elegant way to get the offset of the first different character?

The obvious solution would be:

for ($offs         


        
4条回答
  •  粉色の甜心
    2020-11-28 20:44

    I wanted to add this as as comment to the best answer, but I do not have enough points.

    $string1 = 'foobarbaz';
    $string2 = 'foobarbiz';
    $pos = strspn($string1 ^ $string2, "\0");
    
    if ($pos < min(strlen($string1), strlen($string2)){
        printf(
            'First difference at position %d: "%s" vs "%s"',
            $pos, $string1[$pos], $string2[$pos]
        );
    } else if ($pos < strlen($string1)) {
        print 'String1 continues with' . substr($string1, $pos);
    } else if ($pos < strlen($string2)) {
        print 'String2 continues with' . substr($string2, $pos);
    } else {
        print 'String1 and String2 are equal';
    }
    

提交回复
热议问题