Asked  2 Years ago    Answers:  5   Viewed   38 times

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?



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.

Sunday, October 30, 2022

Not possible. the case items must be VALUES. You have expressions, which means the expressions are evaluated, and the result of that expression is them compared against the value in the switch(). That means you've effectively got

switch(...) { 
  case TRUE: ...
  case TRUE: ...

You cannot use multiple values in a case. YOu can, however, use the "fallthrough support":

switch(...) {
   case 'one':
   case 'two':
       return 'one or two';
   case 'three':
   case 'four':
       return 'three or four';
Saturday, October 29, 2022

function to_lower_and_without_tildes($str,$encoding="UTF-8") {
  $str = preg_replace('/&([^;])[^;]*;/',"$1",htmlentities(mb_strtolower($str,$encoding),null,$encoding));
  return $str;

function compare_function($a,$b) {
  return strcmp(to_lower_and_without_tildes($a), to_lower_and_without_tildes($b));

$array1 = array("a" => "gréen", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_uintersect($array1, $array2,"compare_function");


    [a] => gréen
    [0] => red
Saturday, October 15, 2022

The string type doesn't support this. You're probably best off using the regular expression sub method with the re.IGNORECASE option.

>>> import re
>>> insensitive_hippo = re.compile(re.escape('hippo'), re.IGNORECASE)
>>> insensitive_hippo.sub('giraffe', 'I want a hIPpo for my birthday')
'I want a giraffe for my birthday'
Thursday, September 1, 2022

If you want to do that: just make sure the input data is in all lowercase, and use lowercase cases...

switch ("UPPER".toLowerCase()) {
case  "upper" :


Localization issues

Also, the ages old issue of localization strikes again, and plagues this thing too... For example, in the Turkish Locale, the uppercase counterpart of i is not I, but ?... And in return, the I is not transformed to i, but a "dotless i": ?. Don't underestimate this, it can be a deadly mistake...

Thursday, September 1, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :

Browse Other Code Languages