├── README.md └── SoundsLike.php /README.md: -------------------------------------------------------------------------------- 1 | # php-sounds-like-search 2 | PHP Sounds Like Search Class 3 | 4 | Usage and background: 5 | https://www.codepunker.com/blog/implement-a-sounds-like-search-in-php 6 | -------------------------------------------------------------------------------- /SoundsLike.php: -------------------------------------------------------------------------------- 1 | searchAgainst = $searchAgainst; 15 | $this->input = $input; 16 | } 17 | 18 | /** 19 | *@param $phrase - string 20 | *@return an array of metaphones for each word in a string 21 | */ 22 | private function getMetaPhone($phrase) 23 | { 24 | $metaphones = array(); 25 | $words = str_word_count($phrase, 1); 26 | foreach ($words as $word) { 27 | $metaphones[] = metaphone($word); 28 | } 29 | return $metaphones; 30 | } 31 | 32 | /** 33 | *@return the closest matching string found in $this->searchAgainst when compared to $this->input 34 | */ 35 | public function findBestMatch() 36 | { 37 | $foundbestmatch = -1; 38 | 39 | //get the metaphone equivalent for the input phrase 40 | $tempInput = implode(' ', $this->getMetaPhone($this->input)); 41 | 42 | foreach ($this->searchAgainst as $phrase) 43 | { 44 | //get the metaphone equivalent for each phrase we're searching against 45 | $tempSearchAgainst = implode(' ', $this->getMetaPhone($phrase)); 46 | $similarity = levenshtein($tempInput, $tempSearchAgainst); 47 | 48 | if ($similarity == 0) // we found an exact match 49 | { 50 | $closest = $phrase; 51 | $foundbestmatch = 0; 52 | break; 53 | } 54 | 55 | if ($similarity <= $foundbestmatch || $foundbestmatch < 0) 56 | { 57 | $closest = $phrase; 58 | $foundbestmatch = $similarity; 59 | } 60 | } 61 | 62 | return $closest; 63 | } 64 | 65 | } 66 | --------------------------------------------------------------------------------