Reputation: 41219
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!
Upvotes: 0
Views: 1541
Reputation: 921
Another way to do it is:
<?php
function foo($paragraph){
$parts = explode("\n", $paragraph);
foreach ($parts as $key => $line) {
$line[0] = strtoupper($line[0]);
$parts[$key] = $line;
}
return implode("\n", $parts);
}
$paragraph = "This is the first line.
this is the second line.
we live in Europe.
this is the fourth line.";
echo foo($paragraph);
?>
Upvotes: 1
Reputation: 11171
How about this one?
$a = "This is the first line.\n\r
this is the second line.\n\r
we live in Europe.\n\r
this is the fourth line.";
$a = implode("\n", array_map("ucfirst", explode("\n", $a)));
Upvotes: 5
Reputation: 905
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);
Upvotes: 1
Reputation: 23892
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.
Upvotes: 3