Advertisement
Guest User

Similarity checker

a guest
Jan 27th, 2014
439
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.28 KB | None | 0 0
  1. class Similarity
  2. {
  3.     protected $data = null;
  4.     protected $distance = null;
  5.    
  6.     public function __construct($data, $distance)
  7.     {
  8.         $this->data     = (string)$data;
  9.         $this->distance = (int)$distance;
  10.     }
  11.    
  12.     public function checkMatch($search, callable $checker=null, array $args=[], $return=false)
  13.     {
  14.        $data   = preg_split('/\s+/', strtolower($this->data), -1, PREG_SPLIT_NO_EMPTY);
  15.        $search = trim(preg_replace('/\s+/', ' ', strtolower($search)));
  16.        foreach($this->getAssoc($data, substr_count($search, ' ')+1) as $assoc)
  17.        {
  18.            foreach($this->getPermutations($assoc) as $ordered)
  19.            {
  20.                $ordered = join(' ', $ordered);
  21.                $result  = call_user_func_array($checker, array_merge([$ordered, $search], $args));
  22.                if($result<=$this->distance)
  23.                {
  24.                    return $return?$ordered:true;
  25.                }
  26.            }
  27.        }
  28.        
  29.        return $return?null:false;
  30.     }
  31.    
  32.     protected function getPermutations(array $input)
  33.     {
  34.        if(count($input)==1)
  35.        {
  36.           return [$input];
  37.        }
  38.        $result = [];
  39.        foreach($input as $key=>$element)
  40.        {
  41.           foreach($this->getPermutations(array_diff_key($input, [$key=>0])) as $subarray)
  42.           {
  43.              $result[] = array_merge([$element], $subarray);
  44.           }
  45.        }
  46.        return $result;
  47.     }
  48.    
  49.     protected function nextAssoc($assoc)
  50.     {
  51.        if(false !== ($pos = strrpos($assoc, '01')))
  52.        {
  53.           $assoc[$pos]   = '1';
  54.           $assoc[$pos+1] = '0';
  55.           return substr($assoc, 0, $pos+2).
  56.                  str_repeat('0', substr_count(substr($assoc, $pos+2), '0')).
  57.                  str_repeat('1', substr_count(substr($assoc, $pos+2), '1'));
  58.        }
  59.        return false;
  60.     }
  61.  
  62.     protected function getAssoc(array $data, $count=2)
  63.     {
  64.        if(count($data)<$count)
  65.        {
  66.           return null;
  67.        }
  68.        $assoc   = str_repeat('0', count($data)-$count).str_repeat('1', $count);
  69.        $result = [];
  70.        do
  71.        {
  72.           $result[]=array_intersect_key($data, array_filter(str_split($assoc)));
  73.        }
  74.        while($assoc=$this->nextAssoc($assoc));
  75.        return $result;
  76.     }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement