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

26,857 responses to “Limit the number of newlines in a string”

  1. 68win Avatar

    This site was… how do you say it? Relevant!! Finally I have found
    something which helped me. Thank you!

  2. Jared Edwards Avatar

    This is quite enlightening. Check out defensa legal Vigo for more.

  3. Click Guide Site Avatar

    You ought to be a part of a contest for one of the most useful blogs
    on the web. I’m going to recommend this blog!

  4. Alvin Torres Avatar

    Your details on coping with and employing nang cylinder deliveries efficiently are precisely what I used to be seek—you’ve in actual fact laid the whole lot out neatly, thank you—analyze even more by means of ## nang tanks Melbourne

  5. Arthur Crawford Avatar

    Everyone necessities a collection ofMrCreamChargers of their kitchen—it transforms your cooking revel in!!! ### any keyword ### nang delivery on demand

  6. Benjamin Palmer Avatar

    Appreciate the helpful advice. For more, visit Tarifas taxi Arzúa .

  7. Owen Colon Avatar

    Great information about deck builder in athens ! I’ve been looking into this for a while.

Leave a Reply

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