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

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

  1. please visit Avatar

    Hello, I enjoy reading all of your post. I
    wanted to write a little comment to support you.

  2. stump grinding estimate Avatar

    Hi, i think that i saw you visited my site thus i came to “return the favor”.I am trying to find things to
    improve my web site!I suppose its ok to use some of your ideas!!

    Also visit my website … stump grinding estimate

  3. Video production in cyprus Avatar

    I will right away grasp your rss as I can’t Video production in cyprus finding your email subscription link or e-newsletter service.
    Do you have any? Kindly permit me realize so that I may just subscribe.
    Thanks.

  4. please visit Avatar

    It’s hard to come by knowledgeable people on this
    subject, however, you sound like you know what you’re talking about!
    Thanks

  5. lowest price guaranteed Avatar

    Saved as a favorite, I love your blog!

    Feel free to visit my blog post; lowest price guaranteed

  6. JTime Avatar

    Hello i am kavin, its my first time to commenting anyplace, when i read this article i thought i could also
    make comment due to this sensible piece of writing.

  7. click here Avatar

    I think the admin of this web page is actually working hard for his website, for the reason that here every data is quality based stuff.

  8. this review Avatar

    Hi colleagues, nice piece of writing and good urging commented
    at this place, I am really enjoying by these.

  9. watch now Avatar

    Wow, that’s what I was seeking for, what a information! present here at this weblog, thanks admin of this website.

Leave a Reply

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