Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 607
Amit Verma Avatar asked Dec 22 '15 16:12

Amit Verma


People also ask

What does preg_ replace() return?

The preg_replace() function returns a string or array of strings where all matches of a pattern or list of patterns found in the input are replaced with substrings. There are three different ways to use this function: 1. One pattern and a replacement string.

How do you replace words in regex?

Find/Replace with Regular Expression (Regex) or Wildcards. Word supports find/replace with it own variation of regular expressions (regex), which is called wildcards. To use regex: Ctrl-H (Find/Replace) ⇒ Check "Use wildcards" option under "More".

What is the use of preg_ replace in PHP?

PHP | preg_replace() Function The preg_replace() function is an inbuilt function in PHP which is used to perform a regular expression for search and replace the content.

What is the difference between Str_replace and Preg_replace?

str_replace replaces a specific occurrence of a string, for instance "foo" will only match and replace that: "foo". preg_replace will do regular expression matching, for instance "/f. {2}/" will match and replace "foo", but also "fey", "fir", "fox", "f12", etc.


1 Answers

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.

like image 59
chris85 Avatar answered Oct 10 '22 06:10

chris85