Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform a string to lowercase with preg_replace

I just stuck at this and cannot find solution. I would like to try to transform a string to lower case using preg_replace. I just cannot create the right regex. The reason is that normal strtolower does not support unicode characters. I know that I could use mb_strtolower but this function seems to be quite slow and beside them not everyone has MB support.

Any clue?

Regards, Radek

EDIT: Ok, thanks alot for your help guys. I think my approach was not quite correct. I think it would be much better to use this: How do I detect non-ASCII characters in a string? and then respectively use either the strtolower or mb_strtolower if available.

like image 358
Radek Suski Avatar asked Mar 30 '12 07:03

Radek Suski


People also ask

What is preg_ replace?

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.

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.

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".

Which function is used to replacing pattern in string?

The REGEXREPLACE( ) function uses a regular expression to find matching patterns in data, and replaces any matching values with a new string.


1 Answers

Regex is not able to change characters by itself, it can only change their order and/or add additional characters/delete some of them.

There is preg_replace_callback or /e flag, but they can manipulate only with known functions, and therefore can't do better than strtolower.

If you can't rely on existense of mb_strolower function, you will have to implement it yourself.

like image 196
Nameless Avatar answered Oct 26 '22 17:10

Nameless