0

我似乎无法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;
}
4

1 回答 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]在替换函数中指定,则可以避免。


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

代码:(演示

$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
于 2018-10-04T10:05:58.233 回答