Longest Common Prefix Between Two Strings

While working on a “for fun” side project I needed to get the longest common prefix of two arbitrary strings. Since I didn’t find what I was looking for in the PHP string functions I made my own. And for some perverse reason i decided to see what the fewest number of lines I could do it in was without displaying warnings…

I got down to a one line function, and managed to avoid using an @ to silence anything…


function str_common_prefix( $s1, $s2, $i=0 ) {
return ( !empty($s1{$i}) && !empty($s2{$i}) && $s1{$i} == $s2{$i} ) ? str_common_prefix( $s1, $s2, ++$i ) : $i;
}

I’d be interested to see what others come up with.

5 thoughts on “Longest Common Prefix Between Two Strings

  1. And, yes, I know I've said I hate the ternary operator… but I didn't set out to write the most beautiful version of this, just the shortest… I still believe that the ternary operator makes ugly and unreadable code, exemplified above.

Leave a Reply to apokalyptikCancel reply