Search code examples
phparraysfor-loopcase-sensitive

Need to change case of a string - PHP


$variable = "test_company_insurance_llc_chennai_limited_w-8tyu.pdf";

I need to display above the $variable like

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

For that I've done:

$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
    }   

} 

I've got stuck in the to-do part.

I will change the specific words to uppercase using strtoupper.

Later, how should I need to merge the array?

Any help will be thankful...


Solution

  • $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;