PHP

Levenshtein Similarity Percentage

admin by @admin ADMIN
6m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Wrap PHP's built-in levenshtein() to return a similarity score from 0.0 (totally different) to 1.0 (identical). Handy for "did you mean…?" suggestions.
PHP
Raw
<?php
function similarity(string $a, string $b): float {
    if ($a === $b)             return 1.0;
    if ($a === '' || $b === '') return 0.0;
    $maxLen = max(strlen($a), strlen($b));
    return 1.0 - (levenshtein($a, $b) / $maxLen);
}

printf("%.2f\n", similarity('kitten', 'sitting'));   // 0.57
printf("%.2f\n", similarity('php', 'phpx'));         // 0.75
printf("%.2f\n", similarity('hello', 'hello'));      // 1.00
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.