2013-06-01 23 views
2

大寫字符我下面,它似乎試過沒有工作爲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'; 
} 

這裏有什麼問題?達到預期結果的最佳方法是什麼?

+1

讓我澄清一下這個問題:你想一些特別的角色,成爲小寫,如果是大寫,反之亦然? – raina77ow

+0

@ raina77ow我從這個問題得到同樣的印象。 – wazy

+0

什麼現在不適合你? – karthikr

回答

2

如果要更改整個字符串的大小寫,請嘗試:strtoupper($string)strtolower($string)。如果只想更改字符串首字母的大小寫,請嘗試:ucfirst($string)lcfirst($string)

還有str_replace(),區分大小寫。你可以做一些像str_replace('a', 'A', $string);這樣的全部小寫字母'a'替換爲大寫字母'A'。

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

+0

看起來像他想改變每個元素的情況。 – karthikr

2

它看起來像你試圖反轉案件?

$word = strtolower($word)^strtoupper($word)^$word; 
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 
相關問題