How to replace underscores with spaces and apply title casing to column name strings with preg_replace_callback()?

397 views Asked by At

I can't seem to get the preg_replace() to change to preg_replace_callback().

In an attempt to make database table columns more human-friendly when I display them, I am trying to replace underscores with spaces and make every word start with a capital letter.

function tidyUpColumnName($_colName) {

    // Check for blank and quit
    if(empty($_colName)) return false;

    // Replace underscore and next lowercase letter with space uppercase and Capitalise first letter
    $newColName = ucfirst(preg_replace_callback('/_[a-z]/uis', '" ".substr(strtoupper("$0"), 1)', $_colName));
    return $newColName;
}
1

There are 1 answers

0
mickmackusa On

You cannot use a function in a replacement value with preg_replace() anymore. This is why preg_replace_callback() is used.

preg_replace_callback() expects a function in the second parameter.

preg_replace_callback('/_([a-z])/ui', function($m) { return " " . strtoupper($m[1]); }, $_colName)

You don't need the s pattern modifier because you aren't using any . characters in your pattern.

You can avoid substr() if you use a capture group and nominate $m[1] in your replacement function.


Hmm, if I understand your intent, you don't need regex at all...

Code: (Demo)

$string = "what_the_hey_now";    
// echo ucwords(str_replace("_", " ", $string));  // not multibyte safe
echo mb_convert_case(str_replace("_", " ", $string), MB_CASE_TITLE, "UTF-8");

Output:

What The Hey Now