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?
To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.
You can also sort an array using the sort() method of the Arrays class.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With