1<?php
2
3$input = 'Director, My Company';
4
5// array of words to check against
6$words = array('Foo bar','Lorem Ispum','Director');
7
8// no shortest distance found, yet
9$shortest = -1;
10
11// loop through words to find the closest
12foreach ($words as $word) {
13
14 // calculate the distance between the input word,
15 // and the current word
16 $lev = levenshtein($input, $word);
17
18 // check for an exact match
19 if ($lev == 0) {
20
21 // closest word is this one (exact match)
22 $closest = $word;
23 $shortest = 0;
24
25 // break out of the loop; we've found an exact match
26 break;
27 }
28
29 // if this distance is less than the next found shortest
30 // distance, OR if a next shortest word has not yet been found
31 if ($lev <= $shortest || $shortest < 0) {
32 // set the closest match, and shortest distance
33 $closest = $word;
34 $shortest = $lev;
35 }
36}
37
38echo "Input word: $input\n";
39if ($shortest == 0) {
40 echo "Exact match found: $closest\n";
41} else {
42 echo "Did you mean: $closest?\n";
43}
44