php - PHP中字符串的文本缩写

标签 php codeigniter-2

我正在尝试使用 CodeIgniter 2.x 从头开始​​创建网上商店。一家商店有自己制造商的产品,例如 Glock、Colt、Kalashnikov、Boker、CZ、Kizlyar、GroundZero 等...

我需要为混合了 product.idproduct 的每个产品创建唯一的 SKU (库存单位) 名称.制造商。这样做没有问题,即:SKU 对于具有 id=13manufacturer=GroundZeroname=Striker 的产品II 变为:groundzero-0013

我需要生成缩写,这样 SKU 就变成这样:grzr-0013gnzr-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/

相关文章:

php - 运行 CodeIgniter 项目

javascript - 如何使用 jQuery 修改 POST headers onclick?

php - 如何用 php/html 偏移图像?

php - 如何在搜索中使用 substr 函数

javascript - 不同的结果来自同一领域

php - 为什么 usort (php) 即使不返回整数也能工作?

php - 可编辑,PHP + MySQL

plugins - CodeIgniter - 如何创建插件系统?

php - 当 POST 数组*不*为空时,RESTful 服务会出错