How can we leave only the first uppercase letter of each paragraph?

Asked

Viewed 362 times

-1

In the textarea field, if the user type everything mixed (uppercase and minuscule) in several paragraphs, I need only the first letter of each paragraph capitalized.

If you use ucfirst(strtolower($text)); only the first letter is capitalized for the entire string

how to do it in php before saving?

Thanks in advance for your help

2 answers

0


Answer:

Html (index.html):

<form method="post" action="teste.php">
    <textarea name="texto" cols="50" rows="5"></textarea>
    <input type="submit">
</form>

PHP (test.php):

// Recebe o texto da <textarea>
$texto = (isset($_POST['texto'])) ? $_POST['texto'] : null;

// Transforma os parágrafos em itens de um array
$texto = explode("\n", str_replace("\r", "", $texto));
// Percorre todos os itens do array (todos os paragrafos)
foreach($texto as &$paragrafo){
// Transforma a primeira letra em maiúscula
    $paragrafo = ucfirst(strtolower($paragrafo));
}

// Para ver como ficou o array (Cada item do array é um paragrafo)
print_r($texto);

// Cria um novo array para o foreach
$texto1 = $texto;
// Variável que irá armazenar o texto denovo como string
$novoTexto = "<br><br><br>";
// Percorre todo o array
foreach($texto1 as $valor){
    // Concatena os itens do array em uma sting
    $novoTexto .= "<p>".$valor."</p>";
}
// Mostra o resultado
echo $novoTexto;

  • You are saving the word "Array". I only took print_r($text). Thank you

  • I just took the test here, it’s working properly. The "problem" of saving the word array is because as I mentioned in the first line of code, I transform the string of the <textarea> into an array, where each paragraph is an item, to view the array you should use precisely the print_r(), just the part you took... I’ll edit the answer and put even more chewy...

  • I solved it with implode. I posted it as a response. Your help has served me to research and broaden my horizons. Thank you

  • Good alternative implode to turn the array into string again. I took a look at the answer you posted, only the curiosity title, & de &$paragrafo is no longer needed as there will be no change in the array during foreach. Hug!

0

Solution based on the help of Michellhenrique

I used Implode

// Transforma os parágrafos em itens de um array
$texto = explode("\n", str_replace("\r", "", $texto));
// Percorre todos os itens do array (todos os paragrafos)
foreach($texto as &$paragrafo){
   // Transforma a primeira letra em maiúscula 
   $todos = $todos.ucfirst(strtolower($paragrafo)); // agrupa o explode em $todos 
}   
$texto = implode('', array ($todos)); // remonta o texto correto

Browser other questions tagged

You are not signed in. Login or sign up in order to post.