While trying to fulfill your wish that no explode() function calls are used, I have created two functions that can match using the model number and the manufacturer. The first function matches using a regular expression, while the second using string manipulation. Performance wise I have no idea. They could properly both be optimized A LOT, but the functionality should be there.
The regular expression version has the advantage that it captures the unknown number. This can easily be refactored away if you do not want that functionality. But my guess is that it is somehow important. If not, then why store it in the first place :D
/**
* Finds the first matching phone using a regular expression.
*
* @param array $phones An array of available phones
* @param string $model The model number of the phone
* @param string $manufacturer The manufacturer of the phone
*
* @return array|bool Returns an associative array with matched phone and the
* unknown number on success. Returns FALSE if no match.
*/
function find_phone_regex(array $phones, $model, $manufacturer) {
/*
* OPS: I have added the 'i' flag to make it case-insensitive.
* This might not be the wished behavior.
*/
$regex = '~^' . $model . '-(?<number>[0-9]+)-phone-' . $manufacturer . '$~i';
foreach($phones as $phone) {
if(preg_match($regex, $phone, $matches)) {
return [
'phone' => $phone,
'number' => $matches['number']
];
}
}
return false;
}
/**
* Finds the first matching phone.
*
* @param array $phones An array of available phones
* @param string $model The model number of the phone
* @param string $manufacturer The manufacturer of the phone
*
* @return string|bool Returns the phone on success. Returns FALSE if it does not exist.
*/
function find_phone_string(array $phones, $model, $manufacturer) {
$input_model_pos = strlen($model);
$input_manufacturer_pos = strlen($manufacturer);
$model = strtolower($model);
$manufacturer = strtolower($manufacturer);
foreach($phones as $phone) {
$phone_model = substr($phone, 0, $input_model_pos);
$phone_manufacturer = substr($phone, -$input_manufacturer_pos);
if(strtolower($phone_model) == $model && strtolower($phone_manufacturer) == $manufacturer) {
return $phone;
}
}
return false;
}
The usage for both of them are the same regarding the argument list. Only the function name is different. Using the data you have provided the two function will return the following (displayed with var_dump()).
The regular expression version.
$phone = find_phone_regex($phones, '1845', 'nokia');
array (size=2)
'phone' => string '1845-260-phone-nokia' (length=20)
'number' => string '260' (length=3)
The string version.
$phone = find_phone_string($phones, '1845', 'nokia');
string '1845-260-phone-nokia' (length=20)