baa2w
baa2w

Reputation: 374

Changing case with regex

I was looking for this for a while, but was not able to find any answer. I need to change a string to lowercase in PHP.
Off course, this can be done by using strtolower(), but I was wondering if its possible to do it via preg_replace().
I noticed that in vim one can use \L or \U modifiers in the back references to change the case to lower or upper.

Is something like that possible to do in PHP, i.e. in the second argument in preg_replace()? The reason why I wanna change the case via preg_replace() is that I heard that it might work better for UTF8 strings (not sure if its true).

Thanks.

Upvotes: 1

Views: 126

Answers (2)

Doing with preg_replace is practically impossible.

This is because you need to pass the strtolower() / strtoupper() as a parameter to preg_replace function. Since preg_replace cannot act on their own.

Go with the function what Dave suggested.

Upvotes: 0

dave
dave

Reputation: 64657

You should actually just use

 mb_strtolower($str, 'UTF-8')

That way you specify utf-8 is the encoding, and all should work well.

Edit: sorry had strtoupper, changed to lower. Also, you can leave off utf-8 and it should automatically detect the encoding and use the right one.

Upvotes: 1

Related Questions