Created
August 13, 2020 11:50
-
-
Save sasin91/0ce2cb8225e8c2dcd59898fc690e0416 to your computer and use it in GitHub Desktop.
Str::diff
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Str::macro('diff', function (string $compare, string $to) { | |
// First we'll find the determine the bitwise difference between the two strings, using the bitwise XOR operator (^) to compare them. | |
// Then we'll utilize strspn to determine the position where a difference is found. | |
$from_start = strspn($compare ^ $to, "\0"); | |
// Next we'll determine the end position, by reversing both strings then utilizing strspn as before. | |
$from_end = strspn(Str::reverse($compare) ^ Str::reverse($to), "\0"); | |
// here we snip out original value | |
$value = Str::substr($compare, $from_start, (strlen($compare) - $from_end) - $from_start); | |
// next, the difference to that value. | |
$difference = Str::substr($to, $from_start, (strlen($to) - $from_end) - $from_start); | |
return [ | |
$value => $difference, | |
]; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment