简体   繁体   中英

for php, how to lowercase or uppercase a character in a string

I tried the following, it doesn't seem to work

if ($word[$index] >= 'a' && $word[$index] <= 'z') {
  $word[$index] = $word[$index] - 'a' + 'A';
} else if ($word[$index] >= 'A' && $word[$index] <= 'Z') {
  $word[$index] = $word[$index] - 'A' + 'a';
}

Anything wrong here? What's the best way to achieve the expected result?

If you want to change the case of the entire string, try: strtoupper( $string ) or strtolower( $string ) . If you want to change just the case of the first letter of the string, try: ucfirst( $string) or lcfirst( $string ) .

There is also str_replace() , which is case-sensitive. You could do something like str_replace( 'a', 'A', $string ); to replace all lowercase letter 'a' with uppercase letter 'A'.

You may want to have a look at a list of the php string functions .

看来您是想将案件倒转?

$word =  strtolower($word) ^ strtoupper($word) ^ $word;

If you want to inverse the case of all the letters in the string, here's one possible approach:

$test = 'StAcK oVeЯfLoW';
$letters = preg_split('/(?<!^)(?!$)/u', $test );
foreach ($letters as &$le) {
    $ucLe = mb_strtoupper($le, 'UTF8');
    if ($ucLe === $le) {
        $le = mb_strtolower($le, 'UTF8');
    }
    else {
        $le = $ucLe;
    }
}
unset($le); 
$reversed_test = implode('', $letters);
echo $reversed_test; // sTaCk OvEяFlOw

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM