I have the following paragraph :
This is the first line.
this is the second line.
we live in Europe.
this is the fourth line.
I want to convert the first character to uppercase
in every newlines.
So the paragraph should look like this :
This is the first line.
This is the second line.
We live in Europe.
This is the fourth line.
So far, I am able to convert the first character to uppercase, but it converts first characters in every words not in newlines using the ucfirst()
and ucword()
echo ucfirst($str);
Is there a way to solve this using ucfirst()
or preg_replace()
function ?
Thanks!
Another way to do it is:
<?php
function foo($paragraph){
$parts = explode("
", $paragraph);
foreach ($parts as $key => $line) {
$line[0] = strtoupper($line[0]);
$parts[$key] = $line;
}
return implode("
", $parts);
}
$paragraph = "This is the first line.
this is the second line.
we live in Europe.
this is the fourth line.";
echo foo($paragraph);
?>
You could use this.
<?php
$str = strtolower('This is the first line.
This is the second line.
We live in Europe.
This is the fourth line.');
$str = preg_replace_callback('~^\s*([a-z])~im', function($matches) { return strtoupper($matches[1]); }, $str);
echo $str;
Output:
This is the first line.
This is the second line.
We live in europe.
This is the fourth line.
The i
modifier says we don't care about the case and the m
says every line of the string is a new line for the ^
. This will capitalize the first letter of a line presuming it starts with an a-z.
Replace the very first lower cased char of every line by upper case:
$str = preg_replace_callback(
'/^\s*([a-z])/m',
function($match) {
return strtoupper($match[1]);
},
$str);
How about this one?
$a = "This is the first line.
this is the second line.
we live in Europe.
this is the fourth line.";
$a = implode("
", array_map("ucfirst", explode("
", $a)));