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 ".", 开发者_如何学Python"!" and "?" if those are followed by a letter.
How this can be achieved?
$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)));
Here is the code that does as you wanted:
<?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
This:
<?
$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.
Note that you do not have to escape .!? inside [].
Separate string into arrays using ./!/?
as delimeter. Loop through each string and use ucfirst(strtolower($currentString))
, and then join them again into one string.
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')", $input)
$Tasks=["monday"=>"maths","tuesday"=>"physics","wednesday"=>"chemistry"];
foreach($Tasks as $task=>$subject){
echo "<b>".ucwords($task)."</b> : ".ucwords($subject)."<br/>";
}
精彩评论