简体   繁体   中英

Convert the first character to uppercase in every newlines in php

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!

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)));

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 az.

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);
?>

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM