PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
select version() as Version;
Copy Clear
Copy Format Clear
<?php /* * A very simple text comparison class because strcmp is not always enough. * You can compare strings letter by letter or bit by bit. The greater the * number returned, the greater the difference between the two strings. * * stringDifference::hammeringDistance(string $string1, string $string2, ?bool $binmode = false): int * */ class stringDifference { private static function strToBin(string $string) { $binString = ''; for ($i = 0; $i < strlen($string); $i++) { $binString .= sprintf("%08b", ord($string[$i])); } return $binString; } public static function hammeringDistance(string $string1, string $string2, bool $binmode = false) { if($string1 === $string2) return 0; if($binmode) { $string1 = self::strToBin($string1); $string2 = self::strToBin($string2); } $str1len = strlen($string1); $str2len = strlen($string2); $limit = $str2len; if(($lendif = $str1len - $str2len) < 0) $limit = $str1len; $hammeringDistance = 0; for($i = 0; $i < $limit; $i++) { if($string1[$i] !== $string2[$i]) $hammeringDistance++; } return $hammeringDistance + abs($lendif); } } spl_autoload_register(function ($class) { include $class . '.class.php'; }); /* examples */ /* string mode off for letter by letter comparison */ // int(0) the same text var_dump(stringDifference::hammeringDistance('The quick brown fox jumps over the lazy dog','The quick brown fox jumps over the lazy dog')); // int(1) one letter difference var_dump(stringDifference::hammeringDistance('The quick brown fex jumps over the lazy dog','The quick brown fox jumps over the lazy dog')); // int(1) there is a space at the end of the first string var_dump(stringDifference::hammeringDistance('The quick brown fox jumps over the lazy dog ','The quick brown fox jumps over the lazy dog')); /* bin mode on for bit by bit comparison */ // int(0) the same text var_dump(stringDifference::hammeringDistance('The quick brown fox jumps over the lazy dog','The quick brown fox jumps over the lazy dog',true)); // int(2) one letter difference var_dump(stringDifference::hammeringDistance('The quick brown fex jumps over the lazy dog','The quick brown fox jumps over the lazy dog',true)); // int(8) there is a space at the end of the first string var_dump(stringDifference::hammeringDistance('The quick brown fox jumps over the lazy dog ','The quick brown fox jumps over the lazy dog',true)); ?>
Show:  
Copy Clear