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.
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.
How about:
function str_common_prefix( $s1, $s2 )
{
return strlen($s1^$s2)-strlen(ltrim($s1^$s2,chr(0)));
}
Hmm your software munged the code. The second argument to the ltrim should be "backslash zero".
@[email protected] You're right, weird. I edited it to chr(0) for you. Nice code 🙂
Ah, thanks. I think it'll #fail on non-ascii, but it's a one-liner!