使用preg_replace()和regex用小写替换大写字符串

sta*_*een 7 php regex preg-replace

是否可以使用preg_replace和更换小写的大写字母regex

例如:

以下字符串:

$x="HELLO LADIES!";
Run Code Online (Sandbox Code Playgroud)

我想将其转换为:

 hello ladies!
Run Code Online (Sandbox Code Playgroud)

使用preg_replace():

 echo preg_replace("/([A-Z]+)/","$1",$x);
Run Code Online (Sandbox Code Playgroud)

chr*_*s85 22

我想这就是你想要完成的事情:

$x="HELLO LADIES! This is a test";
echo preg_replace_callback('/\b([A-Z]+)\b/', function ($word) {
      return strtolower($word[1]);
      }, $x);
Run Code Online (Sandbox Code Playgroud)

输出:

hello ladies! This is a test
Run Code Online (Sandbox Code Playgroud)

Regex101演示:https://regex101.com/r/tD7sI0/1

如果你只是希望整个字符串是小写的,而不仅仅是使用整个字符串strtolower.

  • 我不知道strtolower()和preg_replace()在一起会如此简单.谢谢克里斯. (2认同)
  • 很棒的解决方案。我花了很长时间试图查找/找出如何在 PHP 的 PCRE 正则表达式中大写捕获组。我从来没有想到 PHP 可能有自己的本机函数,可以使用 PHP 而不是正则表达式语法来转换捕获组。 (2认同)