Replace an upper-case string with lower-case using preg_replace() and regex

Amit Verma picture Amit Verma · Dec 22, 2015 · Viewed 7.2k times · Source

Is it possible to replace an upper-case with lower-case using preg_replace and regex?

For example:

The following string:

$x="HELLO LADIES!";

I want to convert it to:

 hello ladies!

using preg_replace():

 echo preg_replace("/([A-Z]+)/","$1",$x);

Answer

chris85 picture chris85 · Dec 22, 2015

I think this is what you are trying to accomplish:

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

Output:

hello ladies! This is a test

Regex101 Demo: https://regex101.com/r/tD7sI0/1

If you just want the whole string to be lowercase though than just use strtolower on the whole thing.