2011-07-26 71 views
5

如何只能字符串的最後一個字母爲字符串的最後一個字母的大小寫

例如:

hello 

變爲:

hellO 
+0

一個字符串?你的意思是一段/句子/單詞?否則,你只是在你控制的字符串變量的最後一個位置上執行'strtoupper()'。 –

+4

'echo strrev(ucfirst(strrev(「hello」)))''p – karim79

+0

@ karim79,這比我的想法好得多,你應該把它作爲答案。 – Brad

回答

1

有兩個部分此。首先,你需要知道如何獲得部分字符串。爲此,您需要substr()功能。

接下來,有一個函數用於大寫一個名爲strtotupper()的字符串。

$thestring="Testing testing 3 2 1. aaaa"; 
echo substr($thestring, 0, strlen($thestring)-2) . strtoupper(substr($thestring, -1)); 
12

令人費解而有趣:

echo strrev(ucfirst(strrev("hello"))); 

演示:http://ideone.com/7QK5B

的功能:

function uclast($str) { 
    return strrev(ucfirst(strrev($str))); 
} 
+0

這很好!當我這樣輸入時,但是我想要做的是在wordpress中將頁面標題更改爲全部小寫字母和最後一個字母大寫。例如:現在標題顯示爲Sample Page。我希望它顯示爲示例pagE。繼承人我試過,但它不工作的代碼<?php \t \t \t \t \t $ str = the_title(); \t \t \t \t \t echo strrev(ucfirst(strrev($ str))); \t \t \t \t \t?> – Kathy

+0

對不起,不知道如何在這裏做代碼塊:) – Kathy

+1

@Kathy:'$ str = strtolower(the_title());'然後。如果它不起作用,你的'the_title()'函數可能會出錯。 –

0

這裏有一個算法:

1. Split the string s = xyz where x is the part of 
    the string before the last letter, y is the last 
    letter, and z is the part of the string that comes 
    after the last letter. 
    2. Compute y = Y, where Y is the upper-case equivalent 
    of y. 
    3. Emit S = xYz 
2

$s是您的字符串(Demo):

$s[$l=strlen($s)-1] = strtoupper($s[$l]); 

或函數中的形式:

function uclast($s) 
{ 
    $l=strlen($s)-1; 
    $s[$l] = strtoupper($s[$l]); 
    return $s; 
} 

併爲您的擴展需要擁有的一切小寫,除了最後一個字符明確上 - 大小寫:

function uclast($s) 
{ 
    $l=strlen($s)-1; 
    $s = strtolower($s); 
    $s[$l] = strtoupper($s[$l]); 
    return $s; 
} 
0

小寫字母/大寫字母/混合字符的情況下的所有內容可用於

<?php 
    $word = "HELLO"; 

    //or 

    $word = "hello"; 

    //or 

    $word = "HeLLo"; 

    $word = strrev(ucfirst(strrev(strtolower($word)))); 

    echo $word; 
?> 

輸出的所有單詞

hellO 
相關問題