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);
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.
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".
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With