2016-04-07 13 views
3

現在達成しようとしているのは、単語の最初と最後の文字を大文字にすることです。しかし、これが唯一の今、私はまた、すべての単語の最初の文字を取得する方法を中心に私の心をラップしようとしている、大文字にすべての単語の最後の文字を変更する単語の最初と最後の文字を作る方法(複数の文字列)php

function ManipulateStr($input){ 
    return strrev(ucwords(strrev($input))); 
} 

は現在、これが私の関数であります大文字

例:

入力:こんにちは、私の友人は

出力:こんにちは、私の友人が

おそらく、私はSUBSTRを使用する必要がありますか?しかし、私はこれを複数の単語または1つの単語に適用できるようにするために、どのように見ていますか?

+4

'ucwords(strrev(ucwordsを返します – splash58

+0

あなたの希望する出力をお願いします.. –

+0

@FrayneKonok - それは質問にあります。 '出力:HellO MY FriendS ' – j08691

答えて

5

は初めてstrtolowerを使用して、すべて小文字のあなたの文字列を作成してから最初の文字を大文字にする機能ucwordsを使用し、再度strrevを使用し、他の最初の文字を大文字にするためにucwordsを適用します。 最後にstrrevを使用して、最初と最後の文字を大文字にして元の文字列を戻します。

更新機能

function ManipulateStr($input){ 
    return strrev(ucwords(strrev(ucwords(strtolower($input))))); 
} 
+0

あなたは1 ')' .. – choz

+0

が編集されました。 –

0

あなたは、これが試行してFrayneよりも驚くほど速く機能(〜20%高速化)を探している場合:

function ManipulateStr($input) 
{ 
    return implode(
     ' ', // Re-join string with spaces 
     array_map(
      function($v) 
      { 
       // UC the first and last chars and concat onto middle of string 
       return strtoupper(substr($v, 0, 1)). 
         substr($v, 1, (strlen($v) - 2)). 
         strtoupper(substr($v, -1, 1)); 
      }, 
      // Split the input in spaces 
      // Map to anonymous function for UC'ing each word 
      explode(' ', $input) 
     ) 
    ); 

    // If you want the middle part to be lower-case then use this 
    return implode(
     ' ', // Re-join string with spaces 
     array_map(
      function($v) 
      { 
       // UC the first and last chars and concat onto LC'ed middle of string 
       return strtoupper(substr($v, 0, 1)). 
         strtolower(substr($v, 1, (strlen($v) - 2))). 
         strtoupper(substr($v, -1, 1)); 
      }, 
      // Split the input in spaces 
      // Map to anonymous function for UC'ing each word 
      explode(' ', $input) 
     ) 
    ); 
} 
関連する問題