19

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);
chris85
  • 23,846
  • 7
  • 34
  • 51
Amit Verma
  • 40,709
  • 21
  • 93
  • 115
  • 2
    I don't think you can do that with `preg_replace` alone as there is no pattern. Why not using `strtolower` ? – Alexandre Leprêtre Dec 22 '15 at 16:34
  • Possible duplicate of [How to transform a string to lowercase with preg\_replace](http://stackoverflow.com/questions/9939066/how-to-transform-a-string-to-lowercase-with-preg-replace) – u_mulder Dec 22 '15 at 16:34
  • 5
    Is `strtolower()` to simple a solution? – RiggsFolly Dec 22 '15 at 16:38
  • 2
    `$x="HELLO LADIES!"; $x=strtolower($x);` ;-) as a quick one-liner if you don't need the preg_ function. – Funk Forty Niner Dec 22 '15 at 16:55
  • Possible duplicate of [How to convert array values to lowercase in PHP?](https://stackoverflow.com/questions/11008443/how-to-convert-array-values-to-lowercase-in-php) –  May 08 '18 at 15:16

1 Answers1

43

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.

chris85
  • 23,846
  • 7
  • 34
  • 51
  • 3
    I did not know it would be so easy with strtolower() and preg_replace() together. Thanks chris. – Amit Verma Dec 22 '15 at 16:51
  • 2
    Fantastic solution. I've just spent ages trying to look up / find out how to capitalise a capture group in PHP's PCRE Regex. It never occurred to me that PHP might have its own native function for transforming capture groups using PHP, rather than regex syntax. – Rounin Jun 02 '21 at 12:56