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);
5
  • 2
    I don't think you can do that with preg_replace alone as there is no pattern. Why not using strtolower ? Commented Dec 22, 2015 at 16:34
  • Possible duplicate of How to transform a string to lowercase with preg_replace Commented Dec 22, 2015 at 16:34
  • 5
    Is strtolower() to simple a solution? Commented Dec 22, 2015 at 16:38
  • 2
    $x="HELLO LADIES!"; $x=strtolower($x); ;-) as a quick one-liner if you don't need the preg_ function. Commented Dec 22, 2015 at 16:55
  • Possible duplicate of How to convert array values to lowercase in PHP? Commented May 8, 2018 at 15:16

2 Answers 2

45

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I did not know it would be so easy with strtolower() and preg_replace() together. Thanks chris.
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.
0

Here's a solution using an array of words to be converted to lowercase, which might be useful where you need specific wards to be lowercase (e.g. "VINCENT van GOGH", and "LADIES and GENTLEMEN"):

$x="HELLO LADIES!";
$arr=['hello','ladies']; // words to be set to lower case
$out=$x;
foreach($arr as $v){
    $out=preg_replace('/\b'.$v.'\b/i',$v,$out);
}
echo $out;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.