tags:

views:

175

answers:

3

How can i swap around 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?

+3  A: 

You'll need to iterate through the string testing the case of each character, calling strtolower() or strtoupper() as appropriate, adding the modified character to a new string.

Ignacio Vazquez-Abrams
Any idea how to check the case of a string?
tarnfeld
This will probably work only for ASCII characters. Alternative to `strotolower()` might be `mb_strtolower()`.
Messa
`ctype_lower()` http://php.net/manual/en/function.ctype-lower.php
Ignacio Vazquez-Abrams
I ended up using ctype_upper() but yeah ! thanks :D
tarnfeld
+1  A: 

I suppose a solution might be to use something like this :

$str = "Hello, My Name is Tom";
$newStr = '';
$length = strlen($str);
for ($i=0 ; $i<$length ; $i++) {
    if ($str[$i] >= 'A' && $str[$i] <= 'Z') {
        $newStr .= strtolower($str[$i]);
    } else if ($str[$i] >= 'a' && $str[$i] <= 'z') {
        $newStr .= strtoupper($str[$i]);
    } else {
        $newStr .= $str[$i];
    }
}
echo $newStr;

Which gets you :

hELLO, mY nAME IS tOM


i.e. you :

  • loop over each character of the original string
  • if it's between A and Z, you put it to lower case
  • if it's between a and z, you put it to upper case
  • else, you keep it as-is

The problem being this will probably not work nicely with special character like accents :-(


And here is a quick proposal that might (or might not) work for some other characters :

$str = "Hello, My Name is Tom";
$newStr = '';
$length = strlen($str);
for ($i=0 ; $i<$length ; $i++) {
    if (strtoupper($str[$i]) == $str[$i]) {
        // Putting to upper case doesn't change the character
        // => it's already in upper case => must be put to lower case
        $newStr .= strtolower($str[$i]);
    } else {
        // Putting to upper changes the character
        // => it's in lower case => must be transformed to upper case
        $newStr .= strtoupper($str[$i]);
    }
}
echo $newStr;

An idea, now, would be to use mb_strtolower and mb_strtoupper : it might help with special characters, and multi-byte encodings...

Pascal MARTIN
+1  A: 

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');
If you want to deal with multi-byte UTF-8 characters, you'll need to use strtr($str, $substitutions_array). This is actually the means I use to strip accents from all letters of a UTF8 string.