替换 preg_replace_callback 中的多个匹配项

replacing multiple matches in preg_replace_callback

我有一个字符串 foo_bar_one,我想要实现的是

foo_Bar_One,使用这个正则表达式 /(?<=_)./ 我试图实现一个 preg_replace_callback 但它没有按预期工作,否则我误解了函数的功能。

这是我的方法

preg_replace_callback(
    '/(?<=_)./',
    function ($matches) {
        return strtoupper($matches[0]);
    },
    $model_name
);

它正在匹配并转换为大写,但是什么时候 return?它不会替换实际搜索文本中的 it 吗?

根据preg_replace_callback的return值:

preg_replace_callback() returns an array if the subject parameter is an array, or a string otherwise. On errors the return value is NULL

If matches are found, the new subject will be returned, otherwise subject will be returned unchanged.

这样您就可以捕捉正在 return编辑的内容,例如:

$model_name = "foo_bar_one";
$result = preg_replace_callback(
    '/(?<=_)./',
    function ($matches) {
        return strtoupper($matches[0]);
    },
    $model_name
);

echo $result;

那会给你

foo_Bar_One