对于php,如何在字符串中小写或大写字符

时间:2013-06-01 00:30:01

标签: php

我尝试了以下操作,似乎无法正常工作

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';
}

这里有什么不对吗?达到预期结果的最佳方法是什么?

3 个答案:

答案 0 :(得分:2)

如果您想更改整个字符串的大小写,请尝试:strtoupper( $string )strtolower( $string )。如果您只想更改字符串第一个字母的大小写,请尝试:ucfirst( $string)lcfirst( $string )

还有str_replace(),区分大小写。您可以执行str_replace( 'a', 'A', $string );之类的操作,将大写字母“A”替换为全部小写字母“a”。

您可能需要查看php string functions的列表。

答案 1 :(得分:2)

看起来你试图颠倒这个案子?

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

答案 2 :(得分:2)

如果你想反转字符串中所有字母的大小写,这里有一种可能的方法:

$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
相关问题