簡體   English   中英

除冠詞、連詞和介詞外,每個單詞的首字母大寫

[英]Capitalize first letter of each word with exception of articles, conjunctions, and prepositions

我正在為使用 Codeigniter 構建的自定義 CMS 編寫標簽系統,並且我正在嘗試強制執行特定格式。

基本上,我需要每個單詞的第一個字母大寫,但以下應該是小寫的除外:

  • 文章:一個,一個,該
  • 並列連詞:and、but、or、for、nor等。
  • 介詞(少於五個字母):with、on、at、to、from、by 等。

此外,如果標簽以上述之一開頭,則應大寫。

一些格式正確的標簽示例:

  • 權力的游戲
  • 老鼠和男人
  • 從頭到尾
  • 指環王
  • 極品飛車

到目前為止,我只有:

$tag = 'Lord of the Rings';
$tag = ucwords($tag); 

$patterns = array('/A/', '/An/', '/The/', '/And/', '/Of/', '/But/', '/Or/', '/For/', '/Nor/', '/With/', '/On/', '/At/', '/To/', '/From/', '/By/' );
$lowercase = array('a', 'an', 'the', 'and', 'of', 'but', 'or', 'for', 'nor', 'with', 'on', 'at', 'to', 'from', 'by' );

$formatted_tag = preg_replace($patterns, $lowercase, $tag);

// capitalize first letter of string
$formatted_tag = ucfirst($formatted_tag);

echo $formatted_tag;

這會產生指環王的正確結果,但如何避免重復數組? 當我添加新詞時,將它們匹配起來很乏味。

我確定應該包含一些我遺漏的詞,是否有任何現有的函數或類可以使用?

如果您使用帶有preg_replace_callback()的自定義回調,則不需要$lowercase數組。 此外,您當前的方法需要單詞邊界,否則它將用android替換Android或用band替換bAnd 最后,為 N 個單詞創建 N 個正則表達式是低效且沒有必要的,因為這可以通過一個正則表達式來完成。

我只會保留一個 words 數組:

$words = array('A', 'An', 'The', 'And', 'Of', 'But', 'Or', 'For', 'Nor', 'With', 'On', 'At', 'To', 'From', 'By' );

並創建一個動態正則表達式,完成單詞邊界,如下所示:

$regex = '/\b(' . implode( '|', $words) . ')\b/i';

現在用小寫字母替換所有匹配項:

$formatted_tag = preg_replace_callback( $regex, function( $matches) {
    return strtolower( $matches[1]);
}, $tag);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM