Switch character case, php

后端 未结 9 878
难免孤独
难免孤独 2020-12-05 11:48

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

9条回答
  •  天涯浪人
    2020-12-05 12:42

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

提交回复
热议问题