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

11,455 responses to “Limit the number of newlines in a string”

  1. 동탄출장마사지 Avatar

    I am in fact grateful to the owner of this website who has shared this impressive paragraph at at this place.

  2. Skok Bitrow Avatar

    Good article! We are linking to this great post on our site.
    Keep up the great writing.

  3. best online casino sites Avatar

    When someone writes an piece of writing he/she retains the plan of a user in his/her brain that how a user
    can know it. Therefore that’s why this piece of writing is outstdanding.
    Thanks!

  4. video bokep cina Avatar

    Yesterday, while I was at work, my sister stole my iphone and tested to see if it can survive a forty foot
    drop, just so she can be a youtube sensation. My iPad is now broken and she has
    83 views. I know this is entirely off topic but I had to
    share it with someone!

  5. A8ASZ Avatar

    Howdy! I know this is somewhat off topic but I was wondering if you knew where I
    could locate a captcha plugin for my comment form?
    I’m using the same blog platform as yours and I’m having problems finding one?
    Thanks a lot!

Leave a Reply

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