Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capitalize first letter of first word in a sentence?

I am trying to write a function to clean up user input.

I am not trying to make it perfect. I would rather have a few names and acronyms in lowercase than a full paragraph in uppercase.

I think the function should use regular expressions but I'm pretty bad with those and I need some help.

If the following expressions are followed by a letter, I want to make that letter uppercase.

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

Even better, the function could add a space after ".", "!" and "?" if those are followed by a letter.

How this can be achieved?

like image 230
Enkay Avatar asked Mar 21 '11 20:03

Enkay


People also ask

How do you write the first letter of the beginning word in a sentence?

Capitals signal the start of a new sentence. This is a stable rule in our written language: Whenever you begin a sentence capitalize the first letter of the first word. This includes capitalizing the first word or a direct quotation when it's a full sentence, even if it appears within another sentence.

How do you capitalize the first letter of each word in a string?

To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it.

Which formula will automatically capitalize the first letter of a word 1 point?

The PROPER function will automatically reformat the text so that all words are capitalized. At the same time, it will convert to lowercase all other text. If we also need to strip out extra spaces in the names, we can wrap PROPER in the TRIM function: =TRIM(PROPER(name).

What is it called when you capitalize the first letter of each word?

CamelCase Words are written without spaces, and the first letter of each word is capitalized. Also called Upper Camel Case or Pascal Casing.


2 Answers

How about this? Without Regex.

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

Worked fine for me.

like image 137
Walt Avatar answered Oct 22 '22 17:10

Walt


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

Since the modifier e is deprecated in PHP 5.5.0:

$output = preg_replace_callback('/([.!?])\s*(\w)/', function ($matches) {
    return strtoupper($matches[1] . ' ' . $matches[2]);
}, ucfirst(strtolower($input)));
like image 37
w35l3y Avatar answered Oct 22 '22 16:10

w35l3y