How to avoid excessive line breaks in a textarea

Posted on

Question :

So guys, how can I replace excessive line breaks in a text, so that when I have more than one line break followed these occurrences are replaced by one, regardless of how many were placed. For example:

The text entered by the user:

<textarea>
    Paragráfo de texto
    <br />
    <br />
    Paragráfo de texto
    <br />
    Paragráfo de texto
    <br />
    <br />
    <br />
    Paragráfo de texto
</textarea>

The text to be displayed:

<textarea>
    Paragráfo de texto
    <br />
    Paragráfo de texto
    <br />
    Paragráfo de texto
    <br />
    Paragráfo de texto
</textarea>

I need this in php:)

    

Answer :

Use this:

$html = "Seu conteúdo <br/><br/> quebras e mais quebras";
preg_replace("/(<brs*/?>s*)+/", "<br/>", $html);

Retrieved from: How to convert multiple br tag to single br tag in php

    

The question is vague, but this may resolve:

preg_replace("/[rn]+/", "n", $string_recebida_do_textarea);

Example of how it works:

//Simulando uma string com várias quebras de linha
$str = '
a


b





c
';

// Aqui o resultado sanitizado
// A tag <pre> é desnecessária. Foi colocada para que possa ver pelo browser como se fosse plain/text 
echo '<pre>'.preg_replace("/[rn]+/", "n", $str).'</pre>';

    

Leave a Reply

Your email address will not be published. Required fields are marked *