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

33,007 responses to “Limit the number of newlines in a string”

  1. MMoo Avatar

    For latest news you have to go to see world wide web and on internet I found this website as a
    best site for most recent updates.

  2. digital marketing agency Egypt Avatar

    Post writing is also a excitement, if you be
    familiar with after that you can write if not it is difficult to
    write.

    Also visit my web page … digital marketing agency Egypt

  3. Lester Maxwell Avatar

    I’ve been comparing auto transport quotes for Norfolk, and Norfolk Auto Transport’s had the most transparent pricing.

  4. RIKVIP Avatar

    Can you tell us more about this? I’d want to find out some additional information.

  5. Ora Blake Avatar

    I appreciate the warnings about clogs and leaks! Keeping an eye on plumbing can save so much money. For more plumbing wisdom, visit Melbourne licensed plumber .

  6. Tillie Gordon Avatar

    Great talk on realistic selfies—photo guide at botox. St Johns botox

Leave a Reply

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