Search code examples
phpstringtexttransformcapitalize

How to convert to sentence case each new line?


I'm working on a lyrics website. There is a textarea in the admin panel to inset a new song. How can I do the followings?

  • Capitalize the first letter of each line
  • Add a space at the end of each line

I tried ucfirst(strtolower($str)) which only Capitalize the first letter of the whole word set since there are on periods in it. I know how to remove unnecessary hyphens, extra spaces, and html tags if any. What should I do? using nl2br and replacing <br/> with \n would do everything but capitalizing every new line.


EDIT:

<style>
    textarea { width:200px; height:300px; }
</style>

<form action="/t" method="post">
    <textarea name="txt"><?php echo $_POST["txt"]; ?></textarea>
    <input type="submit" value="OK"/>
    <input type="reset" value="reset"/>
</form>

<?php
$text = $_POST["txt"];
$lines = explode("\n", $text);

foreach($lines as $line)
{
    $line = ucfirst(strtolower($line)) . " ";
}

$goodtext = implode("\n", $lines);

echo "<textarea>$goodtext</textarea>";

?>

EDIT 2

Sample text a user enters in a textarea:

Sithsoi asdigoisad
aASDF asdgdguh asudhg
sadg asdg AAFA ASFA

The desired output :

Sithsoi asdigoisad[sapce]
Aasdf asdgdguh asudhg[sapce]
Sadg asdg aafa asfa[sapce]

Note the capitalized first letter of each line and the [space] at the end of each line


Solution

  • Simplified with array_map():

    <?php
    if(isset($_POST['txt'])) {
        $text = $_POST["txt"]; 
        $text = str_replace("\r\n", "\n", $text);
        $lines = explode("\n", $text); 
        $goodLines = array_map('ucfirst', array_map('strtolower', $lines)); 
        $goodText = implode(" \n", $goodLines); 
        echo nl2br($goodText);
    }
    ?>
    

    Here's a phpfidle that proves it works:

    http://phpfiddle.org/main/code/trr-dgu