levenshtein
Counts how many edits turn one string into another.
Syntax
levenshtein(string $string1, string $string2): intParameters
| Parameter | Type | Description |
|---|---|---|
| $string1 | string | The first string. |
| $string2 | string | The second string. |
Return value
intThe number of character insertions, deletions and replacements.
Examples
A "did you mean" hint:
<?php
$commands = ['install', 'update', 'remove'];
$input = 'instal';
usort($commands, fn ($a, $b) => levenshtein($input, $a) <=> levenshtein($input, $b));
echo $commands[0];Output:
installNotes
The distance is counted in bytes: one non-ASCII letter counts as two edits.
See also
- similar_text — Calculates how similar two strings are.
- soundex — Returns the sound code of an English word.
- strcmp — Compares two strings.
In the tutorial
- Strings — Working with strings in PHP — quotes, concatenation, length, searching, replacing and multibyte functions.