Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Similarity
- {
- protected $data = null;
- protected $distance = null;
- public function __construct($data, $distance)
- {
- $this->data = (string)$data;
- $this->distance = (int)$distance;
- }
- public function checkMatch($search, callable $checker=null, array $args=[], $return=false)
- {
- $data = preg_split('/\s+/', strtolower($this->data), -1, PREG_SPLIT_NO_EMPTY);
- $search = trim(preg_replace('/\s+/', ' ', strtolower($search)));
- foreach($this->getAssoc($data, substr_count($search, ' ')+1) as $assoc)
- {
- foreach($this->getPermutations($assoc) as $ordered)
- {
- $ordered = join(' ', $ordered);
- $result = call_user_func_array($checker, array_merge([$ordered, $search], $args));
- if($result<=$this->distance)
- {
- return $return?$ordered:true;
- }
- }
- }
- return $return?null:false;
- }
- protected function getPermutations(array $input)
- {
- if(count($input)==1)
- {
- return [$input];
- }
- $result = [];
- foreach($input as $key=>$element)
- {
- foreach($this->getPermutations(array_diff_key($input, [$key=>0])) as $subarray)
- {
- $result[] = array_merge([$element], $subarray);
- }
- }
- return $result;
- }
- protected function nextAssoc($assoc)
- {
- if(false !== ($pos = strrpos($assoc, '01')))
- {
- $assoc[$pos] = '1';
- $assoc[$pos+1] = '0';
- return substr($assoc, 0, $pos+2).
- str_repeat('0', substr_count(substr($assoc, $pos+2), '0')).
- str_repeat('1', substr_count(substr($assoc, $pos+2), '1'));
- }
- return false;
- }
- protected function getAssoc(array $data, $count=2)
- {
- if(count($data)<$count)
- {
- return null;
- }
- $assoc = str_repeat('0', count($data)-$count).str_repeat('1', $count);
- $result = [];
- do
- {
- $result[]=array_intersect_key($data, array_filter(str_split($assoc)));
- }
- while($assoc=$this->nextAssoc($assoc));
- return $result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement