aspirinemaga
aspirinemaga

Reputation: 3947

Dynamically abbreviate words and combine with zero-padded ids to generate SKU values

I am trying to create a webshop from scratch using CodeIgniter 2.x. A store have products with it's own manufacturers such as Glock, Colt, Kalashnikov, Boker, CZ, Kizlyar, GroundZero, etc...

I need to create the unique SKU (Stock Keeping Unit) name for each products mixed with product.id and product.manufacturer. There is no problem to do it, i.e.: SKU for a product with id=13, manufacturer=GroundZero and name=Striker II becomes: groundzero-0013

I need to generate the abbreviation so the SKU becomes like this: grzr-0013 or gnzr-0013.

Upvotes: 3

Views: 4587

Answers (1)

HamZa
HamZa

Reputation: 14931

I coded the following SKU generator depending on the specs you mentioned, you may change $l to make it more unique (in a way):

echo SKU_gen('ZeroGround', 13, 2).'<br>'; // zrgr-0013
echo SKU_gen('ZeroGround', 13, 3).'<br>'; // zrgrn-0013
echo SKU_gen('Glock', 14, 3).'<br>'; // glc-0014
echo SKU_gen('CZ', 15, 3).'<br>'; // cz-0015
echo SKU_gen('Kizlyar', 20).'<br>'; // kz-0020

function SKU_gen($string, $id = null, $l = 2){
    $results = ''; // empty string
    $vowels = array('a', 'e', 'i', 'o', 'u', 'y'); // vowels
    preg_match_all('/[A-Z][a-z]*/', ucfirst($string), $m); // Match every word that begins with a capital letter, added ucfirst() in case there is no uppercase letter
    foreach($m[0] as $substring){
        $substring = str_replace($vowels, '', strtolower($substring)); // String to lower case and remove all vowels
        $results .= preg_replace('/([a-z]{'.$l.'})(.*)/', '$1', $substring); // Extract the first N letters.
    }
    $results .= '-'. str_pad($id, 4, 0, STR_PAD_LEFT); // Add the ID
    return $results;
}

Upvotes: 4

Related Questions