Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Pattern Matching from more exact to less in Array

Tags:

php

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

like image 560
SirLouen Avatar asked Mar 15 '23 09:03

SirLouen


1 Answers

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.

like image 165
mcrumley Avatar answered Mar 23 '23 13:03

mcrumley