我正在尝试使用 CodeIgniter 2.x 从头开始创建网上商店。一家商店有自己制造商的产品,例如 Glock、Colt、Kalashnikov、Boker、CZ、Kizlyar、GroundZero 等...
我需要为混合了 product.id
和 product 的每个产品创建唯一的 SKU (库存单位) 名称.制造商
。这样做没有问题,即:SKU 对于具有 id=13
、manufacturer=GroundZero
和 name=Striker 的产品II
变为:groundzero-0013
我需要生成缩写,这样 SKU 就变成这样:grzr-0013 或 gnzr-0013
有什么解决办法吗?
最佳答案
我根据您提到的规范编写了以下 SKU 生成器,您可以更改 $l
以使其更独特(在某种程度上):
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;
}
关于php - PHP中字符串的文本缩写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15830222/