The Fuzzy Search package provides a simple and efficient way to perform fuzzy searches on a collection of texts using the Levenshtein distance algorithm. This package is useful when you need to search for texts that may contain typos or slight variations.
To install the Fuzzy Search package, simply require it in your PHP project using Composer:
composer require designbycode/fuzzy-search
To create a Fuzzy Search instance, you need to pass an array of texts to search and an optional flag for case-insensitive search:
use Designbycode\FuzzySearch\FuzzySearch;
$texts = ['apple', 'banana', 'orange', 'grape'];
$fuzzySearch = new FuzzySearch($texts, true); // Case-insensitive search
To perform a fuzzy search, call the search
method and pass the search query and an optional maximum Levenshtein distance:
$query = 'aple';
$maxDistance = 2;
$results = $fuzzySearch->search($query, $maxDistance);
print_r($results); // Output: ['apple']
The search method returns an array of matching texts, sorted by their Levenshtein distance from the search query.
To get the best match from the search results, call the getBestMatch method:
$bestMatch = $fuzzySearch->getBestMatch($results);
echo $bestMatch; // Output: 'apple'
The Levenshtein Distance Calculator is a utility class that calculates the Levenshtein distance between two strings. This class is used internally by the Fuzzy Search package.
To calculate the Levenshtein distance between two strings, call the calculate method:
use Designbycode\FuzzySearch\LevenshteinDistance;
$str1 = 'kitten';
$str2 = 'sitting';
$distance = LevenshteinDistance::calculate($str1, $str2);
echo $distance; // Output: 3
$texts = ['Apple', 'Banana', 'Orange', 'Grape'];
$fuzzySearch = new FuzzySearch($texts, true);
$query = 'aple';
$maxDistance = 2;
$results = $fuzzySearch->search($query, $maxDistance);
print_r($results); // Output: ['Apple']
$texts = ['apple', 'banana', 'orange', 'grape'];
$fuzzySearch = new FuzzySearch($texts, false);
$query = 'Aple';
$maxDistance = 2;
$results = $fuzzySearch->search($query, $maxDistance);
print_r($results); // Output: []
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.