Title-case words that are separated by underscores

621 Views Asked by At

I'm trying to transform a string to TitleCase before inserting it into my database. I'm using ucwords.

My strings are like: FIRST_SECOND_THIRD

My code:

if (//something){
    $resp = strtolower($line[14]);
    $resp_ = ucwords($resp, "_");

    //rest of the query...

}

var_dump($resp_) returns null and I have no idea why.

2

There are 2 best solutions below

0
Anshu Aditya On

This do exact same thing, Hope will help, cheers.

// php script

<?php

    $string = "FIRST_SECOND_THIRD";

    $var = strtolower(str_replace('_',' ',$string)); 
    $temp = ucwords($var);
    echo str_replace(' ', '', $temp);

?>

//output 
FirstSecondThird

the work could be little easier if the custom delimiter would have worked for the ucwords functions.

0
mickmackusa On

If your input strings are fully uppercase, then your intention is to use strtolower() on the letters that follow the letter that is either at the start of the string or following an underscore.

Code: (Demo)

echo preg_replace_callback(
         '~(?:^|_)[A-Z]\K[A-Z]+~',
         function($m) {
             return strtolower($m[0]);
         },
         'FIRST_SECOND_THIRD'
     );

Output:

First_Second_Third

Even simpler, use mb_convert_case(): (Demo)

echo mb_convert_case('FIRST_SECOND_THIRD', MB_CASE_TITLE, 'UTF-8');
// First_Second_Third