1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* |
5
|
|
|
* @Name : similar-text |
6
|
|
|
* @Programmer : Akpé Aurelle Emmanuel Moïse Zinsou |
7
|
|
|
* @Date : 2019-04-01 |
8
|
|
|
* @Released under : https://github.com/manuwhat/similar-text/blob/master/LICENSE |
9
|
|
|
* @Repository : https://github.com/manuwhat/similar |
10
|
|
|
* |
11
|
|
|
**/ |
12
|
|
|
|
13
|
|
|
|
14
|
|
|
namespace EZAMA{ |
15
|
|
|
class diceDistance extends distance |
16
|
|
|
{ |
17
|
|
|
public static function dice($a, $b, $round = 2) |
18
|
|
|
{ |
19
|
|
|
if ($distance = in_array(self::handleVeryCommonDiceCases($a, $b), array(false, 0.0, 1.0), true)) { |
20
|
|
|
return $distance; |
21
|
|
|
} |
22
|
|
|
static $distance = 0; |
23
|
|
|
static $previous = array(); |
24
|
|
|
if (array($a, $b) === $previous) { |
25
|
|
|
return $distance; |
26
|
|
|
} |
27
|
|
|
$previous = array($a, $b); |
28
|
|
|
$a = self::split($a, 2); |
29
|
|
|
$b = self::split($b, 2); |
30
|
|
|
self::diceDistance($distance, $a, $b, $round); |
31
|
|
|
return $distance; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
private static function handleVeryCommonDiceCases(&$a, &$b) |
35
|
|
|
{ |
36
|
|
|
if (!is_string($a) || !is_string($b)) { |
37
|
|
|
return false; |
38
|
|
|
} |
39
|
|
|
if (empty($a) || empty($b)) { |
40
|
|
|
return 0.0; |
41
|
|
|
} |
42
|
|
|
if ($a === $b) { |
43
|
|
|
return 1.0; |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
private static function diceDistance(&$distance, &$a, &$b, $round) |
48
|
|
|
{ |
49
|
|
|
$ca = ($caGrams = count($a)) * 2 - self::getEndStrLen($a); |
50
|
|
|
$cb = ($cbGrams = count($b)) * 2 - self::getEndStrLen($b); |
51
|
|
|
$distance = round(2 * count($caGrams > $cbGrams ?array_intersect($a, $b) : array_intersect($b, $a)) / ($ca + $cb), $round); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
private static function getEndStrLen($a) |
55
|
|
|
{ |
56
|
|
|
if (function_exists('array_key_last')) { |
57
|
|
|
$end = array_key_last($a); |
58
|
|
|
$end = (isset($end[1])) ? 0 : 1; |
59
|
|
|
} else { |
60
|
|
|
$end = end($a); |
61
|
|
|
$end = (isset($end[1])) ? 0 : 1; |
62
|
|
|
reset($a); |
63
|
|
|
} |
64
|
|
|
return $end; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|