Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array by similarity in relation to an inputted word.

I have on PHP array, for example:

$arr = array("hello", "try", "hel", "hey hello");

Now I want to do rearrange of the array which will be based on the most nearly close words between the array and my $search var.

How can I do that?

like image 460
AimOn Avatar asked Aug 27 '11 22:08

AimOn


People also ask

How do you sort an array based on an object's value?

To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.

How do you sort an array in Word?

You can also sort an array using the sort() method of the Arrays class.


1 Answers

This is a quick solution by using http://php.net/manual/en/function.similar-text.php:

This calculates the similarity between two strings as described in Programming Classics: Implementing the World's Best Algorithms by Oliver (ISBN 0-131-00413-1). Note that this implementation does not use a stack as in Oliver's pseudo code, but recursive calls which may or may not speed up the whole process. Note also that the complexity of this algorithm is O(N**3) where N is the length of the longest string.

$userInput = 'Bradley123';

$list = array('Bob', 'Brad', 'Britney');

usort($list, function ($a, $b) use ($userInput) {
    similar_text($userInput, $a, $percentA);
    similar_text($userInput, $b, $percentB);

    return $percentA === $percentB ? 0 : ($percentA > $percentB ? -1 : 1);
});

var_dump($list); //output: array("Brad", "Britney", "Bob");

Or using http://php.net/manual/en/function.levenshtein.php:

The Levenshtein distance is defined as the minimal number of characters you have to replace, insert or delete to transform str1 into str2. The complexity of the algorithm is O(m*n), where n and m are the length of str1 and str2 (rather good when compared to similar_text(), which is O(max(n,m)**3), but still expensive).

$userInput = 'Bradley123';

$list = array('Bob', 'Brad', 'Britney');

usort($list, function ($a, $b) use ($userInput) {
    $levA = levenshtein($userInput, $a);
    $levB = levenshtein($userInput, $b);

    return $levA === $levB ? 0 : ($levA > $levB ? 1 : -1);
});

var_dump($list); //output: array("Britney", "Brad", "Bob");
like image 135
yceruto Avatar answered Oct 07 '22 02:10

yceruto