How to capitalize first letter of first word in a sentence?
Solution 1:
$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)));
Solution 2:
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
Solution 3:
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 [].
Solution 4:
Separate string into arrays using ./!/?
as delimeter. Loop through each string and use ucfirst(strtolower($currentString))
, and then join them again into one string.
Solution 5:
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.