similar_text(). Percent flag true returns a float percentage; false returns an int match count.
Allows you to create a function which can be used to compute a metric of similarity between two strings. The metric is based on the number of characters that are the same in the two strings. The metric is either returned as numerical value of matching chars or as a percentage. These can either be used as part of a Higher Order Function such as array_map() or as part of a compiled/pipe function.
/**
* @param string $comparisonString The string to compare against base.
* @param bool $asPc If set to true will return the percentage match, rather than char count.
* @return Closure(string):int|float
*/
Strings\similar(string $base, bool $asPc = false): ClosureWhen Strings\similar() is called, it returns the following Closure which can be used like a regular function.
/**
* @param string $string
* @return int|float
* @psalm-pure
*/
$function(string $string): int|floatThis function replaced both Strings\similarAsBase() and Strings\similarAsComparison() as they were both very similar and could be combined into a single function.
This can be used to create a simple closure which can be used as a regular function.
// Create a closure which will look for matches.
$similarCount = Strings\similar('apple');
$similarPc = Strings\similar('apple', true);
// Called as a function.
echo $similarCount('I like them there apples'); // 5
echo $similarPc('I like them there apples'); // 34.48275862068966
// Called as a Higher Order Function.
$array = array_map( $similarCount, ['I like them there apples', 'I like them there pears']);
print_r($array); // [5, 0]This can be called inline using currying.
echo Strings\similar('apple', true)('I like them there apples'); // 34.48275862068966If you are not planning on reusing the Closure created, you can just call it inline with a higher order function as its callable.
$array = array_map(
Strings\similar('apple'),
['I like them there apples', 'I like them there pears']
);
print_r($array); // [5, 0]