Limit the number of newlines in a string

A very short blog post this time. I often use the following short function to limit the number of breaks/newlines in comments that people can submit on a news article or other user input. You can easily limit the number of characters in a comment by using the PHP strlen function, but the comment can still use a lot of vertical space on your website if the user uses 5 breaks in his comment. See the function below to prevent this type of comments:

/**
 * limitBreaks, prevents texts with a lot of enters/breaks after each other
 *
 * @param string $sText
 * @param int $iAmount default 2, numbers of newlines that may occur after eachother
 * @return string, cleaned up string with limited number of newlines
 */
function limitBreaks($sText, $iAmount=2)
{
	return preg_replace("/[\r\n]{".($iAmount+1).",}\t*[\r\n]*/", str_repeat(PHP_EOL, $iAmount), $sText);
}

As you can see a simple but effective function.

Comments

14,455 responses to “Limit the number of newlines in a string”

  1. Thomastraro Avatar

    Выбор транспортного средства зависит исключительно от ваших планов. Для семейного отдыха с детьми лучше выбрать вместительный седан или минивэн. Важный этап — внимательное изучение договора. Обращайте внимание на политику в отношении топлива (полный бак/полный возврат). Для аренды обычно необходимы паспорт, национальные водительские права (иногда с завершенным переводом) и кредитная карта на имя водителя. https://theforge.tankdaddy.com/discuss/showthread.php?tid=97747 Аренда авто в районе кунду

  2. lừa đảo chiếm đoạt tài sản Avatar

    My spouse and I stumbled over here coming from a different web page
    and thought I might as well check things out. I like what I see so now i am following you.
    Look forward to looking over your web page repeatedly.

  3. retinal vs retinol Avatar

    Thank you for sharing your thoughts. I really appreciate your efforts and I will be waiting for your further
    write ups thank you once again.

  4. Mad войти Avatar

    Today, I went to the beach with my kids. I found a sea shell and gave
    it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed.
    There was a hermit crab inside and it pinched her ear. She never wants to go back!
    LoL I know this is totally off topic but I had to tell someone!

  5. vm88 Avatar

    I like the valuable info you provide in your articles.
    I’ll bookmark your weblog and check again here regularly.

    I’m quite sure I’ll learn many new stuff right
    here! Good luck for the next!

Leave a Reply

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