dtqjbbr5283 2017-09-02 23:35
浏览 15

PHP - 这是进行这些更改的有效方法吗?

I care a lot about capitalization (probably too much). So I wrote a function that fixes the capitalization everywhere on my site. I basically want "title case" but with some exceptions... words I don't like to see capitalized and acronyms.

function my_capitals($string)
{
    $uc = ucwords($string);
    $tokens = explode(' ',$uc);
    foreach ($tokens as $key=>$val)
    {
        if ($val == 'Ipa') $tokens[$key] = 'IPA';
        else if ($val == 'Ipas') $tokens[$key] = 'IPAs';
        else if ($val == 'Apa') $tokens[$key] = 'APA';
        else if ($val == 'Apas') $tokens[$key] = 'APAs';
        else if ($val == 'A') $tokens[$key] = 'a';
        else if ($val == 'And') $tokens[$key] = 'and';
        else if ($val == 'The') $tokens[$key] = 'the';
        else if ($val == 'In') $tokens[$key] = 'in';
        else if ($val == 'Or') $tokens[$key] = 'or';
        else if ($val == 'Of') $tokens[$key] = 'of';
        else if ($val == 'To') $tokens[$key] = 'to';
        else if ($val == 'On') $tokens[$key] = 'on';
        else if ($val == 'At') $tokens[$key] = 'at';
        else $tokens[$key] = $val;
    }
    $final = implode(' ',$tokens);
    return $final;
}

Imagine there might be another 10-15 options and that it may be run 3-5 times per page on relatively short strings (one-line descriptions and titles).

My question is this: Is this an efficient way to accomplish this sort of translation? Or should I be figuring out a more efficient way to do it? Is there another alternative I don't know of, as opposed to just switch which probably has similar performance?

  • 写回答

3条回答 默认 最新

  • dongtuo6562 2017-09-03 00:04
    关注

    I would do it this way:

       function my_capitals($string)
        {
            $uc = ucwords($string);
            $tokens = explode(' ',$uc);
            $excepsions = ['Ipa'=>'IPA','Ipas'=>'IPAs'];
            foreach ($tokens as $key=>$val)
            {
                if(isset($excepsions[$val])){
                    $tokens[$key] = $excepsions[$val];
                }
            }
            $final = implode(' ',$tokens);
            return $final;
        }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)