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?
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?
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';
}
<?php
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");
print_r($result);
output:
Array
(
[a] => gréen
[0] => red
)
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'
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" :
....
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...
You'll need to iterate through the string testing the case of each character, calling
strtolower()
orstrtoupper()
as appropriate, adding the modified character to a new string.