2011-11-16 118 views
1

我在句子情況下使用了格式化函數。我的PHP腳本功能是使用函數進行字符串大小寫轉換

function sentence_case($string) { 
    $sentences = preg_split(
     '/([.?!]+)/', 
     $string, 
     -1, 
     PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE 
    ); 

    $new_string = ''; 
    foreach ($sentences as $key => $sentence) { 
     $new_string .= ($key & 1) == 0 
      ? ucfirst(strtolower(trim($sentence))) 
      : $sentence . ' '; 
    } 
    $new_string = preg_replace("/\bi\b/", "I", $new_string); 
    //$new_string = preg_replace("/\bi\'\b/", "I'", $new_string); 
    $new_string = clean_spaces($new_string); 
    $new_string = m_r_e_s($new_string); 
    return trim($new_string); 
} 

雖然它的進行得很好,並且將整個字符串轉換成了句子。但我希望它能在單引號中跳過字符。像我的字符串HeLLO world! HOw aRE You.正在轉換爲Hello world! How are you?,但我想跳過單引號中的內容。就像我希望在單引號中跳過單詞一樣。 'HELLO' World並將單引號中的單詞轉換爲大寫,否則字符串應保留在句子大小寫中。

+0

只是單挑:你會遇到各種各樣的麻煩與專有名詞。 –

+0

我知道我的英語很差... –

+0

我不認爲他的意思是說你的英語不好,但應該把大寫的專有名詞。 –

回答

3

您可以在單引號中添加另一個簡單的正則表達式回調到大寫單詞。 (這是我的理解,你想做的事情。)

$new_string = preg_replace("/'(\w+)'/e", 'strtoupper("\'$1\'")', $new_string); 

如果您希望這每帖多個單詞的工作,代替\w+使用[\w\s]+。但是,這將使文本內出現像isn't這樣的短語更可能失敗。

+0

將其添加到字符串中。像'\''HELLO \''世界。你好嗎? –

+0

它的輸出斜槓。 –

+0

哦,太奇怪了。在'strtoupper(..)'周圍添加'stripslashes(...)' – mario

2

下面是此任務的緊湊和工作液:

$s = preg_replace_callback("~([\.!]\s*\w)|'.+?'~", function($args) { 
     return strtoupper($args[sizeof($args) - 1]); 
    }, ucfirst(strtolower($s))); 

對於以下輸入:

$s = "HeLLO world! HOw aRE You 'HELLo' iS QuOTed and 'AnothEr' is quoted too"; 

它會產生:

Hello world! How are you 'HELLO' is quoted and 'ANOTHER' is quoted too 

附: 如果您使用的是PHP < 5.3,則可以將回調移動到單獨的函數中。

相關問題