Alex Rivera | Logout

Invert case of all letters in a string (uppercase to lowercase and lowercase to uppercase)

Asked 2010-02-14T00:22:18.850
15

How can I swap around / toggle the case of the characters in a string, for example:

$str = "Hello, My Name is Tom";

After I run the code I get a result like this:

$newstr = "hELLO, mY nAME Is tOM";

Is this even possible?

Edit
Report

1 Answer

69

If your string is ASCII only, you can use XOR:

$str = "Hello, My Name is Tom";

print strtolower($str) ^ strtoupper($str) ^ $str;

Outputs:

hELLO, mY nAME IS tOM
answered 2011-07-07T14:47:27.993

Your Answer