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

50,306 responses to “Limit the number of newlines in a string”

  1. Patrick Douglas Avatar

    Houston rebates are limited, so repair can be smarter; I verified incentives through water heater houston .

  2. simontok Avatar

    Thanks to my father who informed me regarding this blog,
    this web site is really amazing.

  3. Francis Garner Avatar

    Love the early morning routine—mine’s set up via local dog walkers Chandler .

  4. Robert White Avatar

    The algae stains near sprinklers drove me nuts until vinyl fence repair santa ana recommended a mild detergent mix—no bleach needed.

  5. Bruce Holland Avatar

    Barbershop pricing strategies can be tricky. I used a calculator template from Richardson, TX barbershop .

  6. tr88 Avatar

    An outstanding share! I’ve just forwarded this onto
    a colleague who was conducting a little research on this.
    And he actually ordered me breakfast because I stumbled upon it for him…

    lol. So let me reword this…. Thank YOU for the meal!!
    But yeah, thanx for spending time to talk about this topic here on your site.

Leave a Reply

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