2011-03-21 136 views
8

我想寫一個函數來清理用戶輸入。如何將句首字母的首字母大寫?

我不是想讓它完美。我寧願用小寫字母表示一些名字和縮略詞,而不用大寫字母的全段。

我認爲這個函數應該使用正則表達式,但是我對這些很不好,我需要一些幫助。

如果下面的表達式後面跟着一個字母,我想讓該字母大寫。

"." 
". " (followed by a space) 
"!" 
"! " (followed by a space) 
"?" 
"? " (followed by a space) 

更好的是,該功能可以在「。」,「!」之後添加空格。和「?」如果那些後面跟着一封信。

這是如何實現的?

+1

好東西,它與論壇無關。而不是假設我想要做什麼,如何幫助? – Enkay 2011-03-21 20:55:21

+2

你不需要任何更多的信息。我解釋了我想要做的事。如果你能提供幫助,那麼請這樣做,但如果不能,請在別的地方去追蹤。 – Enkay 2011-03-21 21:00:37

+2

@Dagon @Enkay請相互尊重。 @Dagon如果您想從@Enkay獲得某些特定的內容,那麼請問該如何處理? – marcog 2011-03-21 21:10:04

回答

30
$output = preg_replace('/([.!?])\s*(\w)/e', "strtoupper('\\1 \\2')", ucfirst(strtolower($input))); 

由於修改é已被棄用的PHP 5.5.0:

$output = preg_replace_callback('/([.!?])\s*(\w)/', function ($matches) { 
    return strtoupper($matches[1] . ' ' . $matches[2]); 
}, ucfirst(strtolower($input))); 
+0

謝謝。這工作。 – Enkay 2011-03-21 21:23:36

+1

沒有問題。:) – w35l3y 2011-03-21 23:05:57

+5

只是提醒,e修飾符已被棄用在PHP 5.5 – 2013-06-14 09:37:38

1

使用./!/?作爲分隔符將字符串分隔成數組。遍歷每個字符串並使用ucfirst(strtolower($currentString)),然後再將它們連接成一個字符串。

+0

有趣的採取。我會試一試。我希望稍微練習一下我的正則表達式,但這可以完成這項工作。謝謝。 – Enkay 2011-03-21 21:04:56

3

這裏是做你想要的代碼:

<?php 

$str = "paste your code! below. codepad will run it. are you sure?ok"; 

//first we make everything lowercase, and 
//then make the first letter if the entire string capitalized 
$str = ucfirst(strtolower($str)); 

//now capitalize every letter after a . ? and ! followed by space 
$str = preg_replace_callback('/[.!?] .*?\w/', 
    create_function('$matches', 'return strtoupper($matches[0]);'), $str); 

//print the result 
echo $str . "\n"; 
?> 

OUTPUT:Paste your code! Below. Codepad will run it. Are you sure?ok

+0

你不再需要create_function :))( – dynamic 2011-03-21 21:09:38

1
$output = preg_replace('/([\.!\?]\s?\w)/e', "strtoupper('$1')", $input) 
1

此:

<? 
$text = "abc. def! ghi? jkl.\n"; 
print $text; 
$text = preg_replace("/([.!?]\s*\w)/e", "strtoupper('$1')", $text); 
print $text; 
?> 

Output: 
abc. def! ghi? jkl. 
abc. Def! Ghi? Jkl. 

注意,你^h大逃亡。!?在[]內。

0

這個怎麼樣?沒有正則表達式。

$letters = array(
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' 
); 
foreach ($letters as $letter) { 
    $string = str_replace('. ' . $letter, '. ' . ucwords($letter), $string); 
    $string = str_replace('? ' . $letter, '? ' . ucwords($letter), $string); 
    $string = str_replace('! ' . $letter, '! ' . ucwords($letter), $string); 
} 

對我來說工作很好。