找到数组中最长的匹配字符串

I have an array of hierarchically arranged identifiers (SNMP sysObjectIDs), that I'd like to match against in order to find the closest match.

For example, if my array contains :

.1.3.6.1.4.1.207         = alliedware
.1.3.6.1.4.1.207.1.14    = alliedwareplus
.1.3.6.1.4.1.207.1.4.126 = allied-radlan
.1.3.6.1.4.1.207.1.4.125 = allied-radlan

And I search for

.1.3.6.1.4.1.207.1.14.69

I would like it to return the alliedwareplus entry.

If I search for

.1.3.6.1.4.1.207.1.4

It should return the alliedware entry.

Basically I just want to return the longest match starting from the beginning of the string.

Thanks in advance!

  1. Sort the array by the number of components in the object ID, from high to low.
  2. Loop through the array, testing whether the object ID in the array is a prefix of the input object ID.
  3. When you find a match like this, break out of the loop.

All these steps will probably be easiest if you first convert all the object IDs to an array:

$objid_arr = explode('.', $objid);

This worked for me and returns the correct test results based on your description.

function find_match($data,$search) {
  $keys = array_keys($data);

  usort($keys,function($a,$b){
    return strlen($b)-strlen($a);
  });

  foreach($keys as $key){
    if (substr($search,0,strlen($key)) == $key)
      return $data[$key];
  }
}

$data = array(
  '.1.3.6.1.4.1.207'         => 'alliedware',
  '.1.3.6.1.4.1.207.1.14'    => 'alliedwareplus',
  '.1.3.6.1.4.1.207.1.4.126' => 'allied-radlan',
  '.1.3.6.1.4.1.207.1.4.125' => 'allied-radlan',
);

find_match($data,'.1.3.6.1.4.1.207.1.14.69'); // => 'alliedwareplus'
find_match($data,'.1.3.6.1.4.1.207.1.4');     // => 'alliedware'