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;
}
You cannot use a function in a replacement value with
preg_replace()
anymore. This is whypreg_replace_callback()
is used.preg_replace_callback()
expects a function in the second parameter.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)
Output: