Switch character case, php

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

OK I know you've already got an answer, but the somewhat obscure strtr() function is crying out to be used for this ;)

$str = "Hello, My Name is Tom";
echo strtr($str, 
           'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
           'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');

Very similar in function to the answer by Mark.

preg_replace_callback(
    '/[a-z]/i',
    function($matches) {
        return $matches[0] ^ ' ';
    },
    $str
)

Tags:

Php

String

Case