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?
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.
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.
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).
CamelCase Words are written without spaces, and the first letter of each word is capitalized. Also called Upper Camel Case or Pascal Casing.
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.
$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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With