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

17,003 responses to “Limit the number of newlines in a string”

  1. best crypto casino Avatar

    I’ve been exploring for a bit for any high quality articles or weblog posts in this sort of area .
    Exploring in Yahoo I ultimately stumbled upon this website.

    Reading this information So i’m happy to convey that I’ve an incredibly excellent uncanny feeling I came upon just what I needed.
    I such a lot for sure will make sure to don?t disregard this site
    and provides it a glance on a relentless basis.

  2. 주소 링크 사이트 Avatar

    Greetings! Very helpful advice in this particular post!
    It is the little changes that make the most important changes.

    Many thanks for sharing!

  3. Prothots Avatar

    Informative and easy to understand legal content.
    Articles like this are helpful for anyone looking to learn more about legal rules, responsibilities, and proper legal procedures.

Leave a Reply

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