【问题标题】:Need to change case of a string - PHP需要更改字符串的大小写 - PHP
【发布时间】:2014-09-17 10:25:00
【问题描述】:
$variable = "test_company_insurance_llc_chennai_limited_w-8tyu.pdf";

我需要在$变量上方显示

Test Company Insurance LLC Chennai Limited W-8TYU.pdf

为此我已经完成了:

$variable = str_replace("_"," ","test_company_insurance_llc_chennai_limited_w-8tyu.pdf");

$test  = explode(" ", $variable);
$countof = count($test);

for ($x=0; $x<$countof; $x++) {

    if($test[$x] == 'w-8tyu' || $test[$x] == 'llc') {
       $test[$x] = strtoupper($test[$x]);
       //todo
    }   

} 

我被困在待办事项部分。

我将使用 strtoupper 将特定单词更改为大写。

稍后,我应该如何合并数组?

任何帮助将不胜感激......

【问题讨论】:

标签: php arrays for-loop case-sensitive


【解决方案1】:
$str_in = "test_company_insurance_llc_chennai_limited_w-8tyu.pdf";
$lst_in = explode("_", $str_in);
$lst_out = array();
foreach ($lst_in as $val) {
    switch($val) {
        case "llc"          : $lst_out[] = strtoupper($val);
                              break;
        case "w-8tyu.pdf"   : $lst_temp = explode('.', $val);
                              $lst_out[] = strtoupper($lst_temp[0]) . "." . $lst_temp[1];
                              break;
        default             : $lst_out[] = ucfirst($val);
    }
}
$str_out = implode(' ', $lst_out);
echo $str_out;

【讨论】:

    【解决方案2】:

    不是很优雅,但可能稍微灵活一些。

    $v = str_replace("_"," ","test_company_insurance_llc_chennai_limited_w-8tyu.pdf");
    
    $acronyms = array('llc', 'w-8tyu');
    $ignores  = array('pdf');
    
    $v = preg_replace_callback('/(?:[^\._\s]+)/', function ($match) use ($acronyms, $ignores) {
        if (in_array($match[0], $ignores)) {
            return $match[0];
        }
    
        return in_array($match[0], $acronyms) ? strtoupper($match[0]) : ucfirst($match[0]);
    }, $v);
    
    echo $v;
    

    如果您将扩展名与初始值分开,则可以删除忽略。

    【讨论】:

      【解决方案3】:

      请参阅下面的代码。我已经按照您的预期打印了代码的输出。所以运行它并回复我...

      $variable = str_replace("_"," ","test_company_insurance_llc_chennai_limited_w-8tyu.pdf");
      
      $test  = explode(" ", $variable);
      $countof = count($test);
      
      for ($x=0; $x<$countof; $x++) {
      
      if($test[$x] == 'llc') {
         $test[$x] = strtoupper($test[$x]);
         //todo
      }elseif($test[$x] == 'w-8tyu.pdf'){
        $file=basename($test[$x],'pdf');
        $info = new SplFileInfo($test[$x]);
        $test[$x] = strtoupper($file).$info->getExtension();
      }
      else{
        $test[$x]=ucfirst($test[$x]);
      }
      }
      echo '<pre>';
      print_r($test);
      echo '</pre>';
      echo $output  = implode(" ", $test);
      

      【讨论】:

        猜你喜欢
        • 2011-01-07
        • 2021-03-30
        • 2014-02-04
        • 1970-01-01
        • 2011-10-11
        • 1970-01-01
        • 2011-05-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多