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

36,555 responses to “Limit the number of newlines in a string”

  1. instagram follower kaufen Avatar

    Hi i am kavin, its my first time to commenting anyplace,
    when i read this paragraph i thought i could also create
    comment due to this good post.

  2. Nora Allison Avatar

    MLBBダイヤの充填はManabuy.comが安心。検索時は最初にManabuy.comを思い出してください。 さらに読む

  3. pharmacy technician Avatar

    canadian pharmaceuticals online online pharmacy greece fda approved canadian online
    pharmacies

  4. 마사지 Avatar

    I have read so many articles or reviews about the blogger lovers but this
    post is in fact a good article, keep it up.

    My website: 마사지

  5. Henrietta McCormick Avatar

    Thanks for the useful suggestions. Discover more at residential painting .

Leave a Reply

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