preg_replace在引用后大写字母

Sum*_*mer 18 php regex

我的名字是这样的:

$str = 'JAMES "JIMMY" SMITH'
Run Code Online (Sandbox Code Playgroud)

我跑strtolower,然后ucwords,它返回:

$proper_str = 'James "jimmy" Smith'
Run Code Online (Sandbox Code Playgroud)

我想把第一个字母是双引号的第二个字母大写.这是正则表达式.似乎strtoupper不起作用 - regexp只返回未更改的原始表达式.

$proper_str = preg_replace('/"([a-z])/',strtoupper('$1'),$proper_str);
Run Code Online (Sandbox Code Playgroud)

有线索吗?谢谢!!

cle*_*tus 35

可能最好的方法是使用preg_replace_callback():

$str = 'JAMES "JIMMY" SMITH';
echo preg_replace_callback('!\b[a-z]!', 'upper', strtolower($str));

function upper($matches) {
  return strtoupper($matches[0]);
}
Run Code Online (Sandbox Code Playgroud)

您可以使用e(eval)标志,preg_replace()但我通常建议不要这样做.特别是在处理外部输入时,它可能非常危险.

  • 正如@mcfedr所提到的,从PHP 5.3开始你可以使用[匿名函数](http://www.php.net/manual/en/functions.anonymous.php):`preg_replace_callback(...,function($)匹配){...` (2认同)

mcf*_*edr 21

使用preg_replace_callback- 但您不需要添加额外的命名函数,而是使用匿名函数.

$str = 'JAMES "JIMMY" SMITH';
echo preg_replace_callback('/\b[a-z]/', function ($matches) {
     return strtoupper($matches[0]);
}, strtolower($str));
Run Code Online (Sandbox Code Playgroud)

使用的/e是被弃用的PHP 5.5和PHP中不起作用7


Gum*_*mbo 20

使用e修饰符来评估替换:

preg_replace('/"[a-z]/e', 'strtoupper("$0")', $proper_str)
Run Code Online (Sandbox Code Playgroud)

其中$0包含整个模式的匹配,所以"和小写字母.但这并不重要,因为"发送时不会改变strtoupper.

  • 显然,`e`选项是一个严重的安全漏洞,他们建议使用`preg_replace_callback()`.仅供参考. (24认同)
  • 自PHP 5.5.0起,此功能已被弃用.非常不鼓励依赖此功能. (9认同)
  • / e将不再适用于PHP 7 http://php.net/manual/en/function.preg-replace.php#refsect1-function.preg-replace-changelog (6认同)