如何用空格替换下划线并使用preg_replace_callback()将标题大小写应用于列名字符串?

问题描述 投票:0回答:1

我似乎无法让preg_replace()改为preg_replace_callback()

为了使数据库表列在显示时更加人性化,我试图用空格替换下划线并使每个单词以大写字母开头。

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;
}
php regex preg-replace-callback title-case
1个回答
1
投票

您不能再使用preg_replace()替换值中的函数。这就是使用preg_replace_callback()的原因。

preg_replace_callback()期望在第二个参数中有一个函数。

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

您不需要s模式修饰符,因为您没有在模式中使用任何.字符。

如果您使用捕获组并在替换函数中指定substr(),则可以避免使用$m[1]


嗯,如果我理解你的意图,你根本就不需要正则表达式......

代码:(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");

输出:

What The Hey Now
© www.soinside.com 2019 - 2024. All rights reserved.