I'm trying to create a function in PHP that matches an string lets say "1234567" with the best suiting match prefix, despite there are multiple matches, select the best.
For example if we have all this:
(1, 12, 123, 1234, 456, 56, 7, 3456, 234567)
Input = "1234567"
The output should be = "1234"
Because the prefix that matches the best (despite 1, 12, and 123 match also are not better than 1234 and despite 234567 is the best match overall, is not a prefix).
I don't know if this functionallity is implemented by default in the language PHP
Sort the prefixes by length from longest to shortest. Then return the first match.
function bestMatch($input, $prefixes)
{
usort($prefixes, function($a, $b) { return strlen($b) - strlen($a); });
foreach ($prefixes as $prefix) {
if (strncmp($input, $prefix, strlen($prefix)) === 0) {
return $prefix;
}
}
return false; // or whatever you want to return for "no match"
}
If you need to do this many times with the same prefix list, you might want to sort the list once and just do the foreach
loop to prevent sorting multiple times.
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