簡體   English   中英

如何將句子中第一個單詞的首字母大寫?

[英]How to capitalize first letter of first word in a sentence?

我正在嘗試編寫一個函數來清理用戶輸入。

我並不想讓它變得完美。 我寧願用小寫的名字和首字母縮略詞比用大寫的完整段落。

我認為該函數應該使用正則表達式,但我很糟糕,我需要一些幫助。

如果下面的表達式后跟一個字母,我想把那個字母寫成大寫。

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

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

如何實現這一目標?

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

由於修飾符e在PHP 5.5.0中已棄用:

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

這是您想要的代碼:

<?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";
?>

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

使用./!/?將字符串分隔成數組./!/? 作為界限。 循環遍歷每個字符串並使用ucfirst(strtolower($currentString)) ,然后將它們再次連接到一個字符串中。

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

這個:

<?
$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.

請注意,您不必逃!? 在里面[]。

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

$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);
}

為我工作得很好。

$Tasks=["monday"=>"maths","tuesday"=>"physics","wednesday"=>"chemistry"];

foreach($Tasks as $task=>$subject){

     echo "<b>".ucwords($task)."</b> : ".ucwords($subject)."<br/>";
}

暫無
暫無

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

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