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

13,059 responses to “Limit the number of newlines in a string”

  1. bet88 đăng nhập Avatar

    Good web site you have got here.. It’s hard to find high
    quality writing like yours these days. I really appreciate people like you!

    Take care!!

  2. https://www.dziennikpowiatowy.pl Avatar

    I enjoy this site – its so usefull and helpfull.

    https://www.dziennikpowiatowy.pl

  3. Teploogotraro Avatar
    Teploogotraro

    Want quick rewards? Use this sportsbook gift code and join the game with added value. Easy to claim and great for any sports enthusiast. https://cdsonla.edu.vn/index.php/vi/component/k2/item/25-getting-to-know-your-professors?tmpl=component&print=1&start=18 Registration bonus betting

  4. Weg Vexaria Avatar

    Way cool! Some very valid points! I appreciate you writing this article and also the rest of
    the website is also really good.

  5. online casino slots real money Avatar

    What’s up, just wanted to mention, I loved this post. It was
    practical. Keep on posting!

  6. smm panel terjamin murah Avatar

    Hi, every time i used to check web site posts here in the early
    hours in the dawn, since i like to find out more and more.

  7. Arbinio Avatar

    Great post. I was checking constantly this blog and I’m impressed!
    Extremely helpful information specially the last part 🙂 I care for such info
    a lot. I was seeking this certain information for a very long time.
    Thank you and good luck.

  8. url analytics Avatar

    Pretty nice post. I just stumbled upon your weblog and wanted to say
    that I have truly enjoyed browsing your blog posts.
    After all I will be subscribing to your rss feed and I hope you write again soon!

Leave a Reply

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