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

27,851 responses to “Limit the number of newlines in a string”

  1. press release Avatar

    Здравствуйте пишу коммент, вдруг кому-то будет интересно.

    Я из Беларуси, давно увлекаюсь онлайн-геймингом, и всё началось с
    того, что мне стало скучно и я решил попробовать читы в пара своих любимых игр.

    Скажу честно, иногда подпитывался энергетиком,
    чаще всего пил Red Bull — и оно
    как-то добавляло драйва. Я обожаю игры по аниме, в особенности играл в Genshin Impact.

    Но дальше началось самое интересное:
    мой аккаунт в Steam забанили. Античит словил модификации
    и мгновенно дал пермач.
    Я знал, что так может случиться,
    но всё равно обидно, ведь столько всего было куплено.

    И да, здесь есть ссылка, рекомендую
    глянуть — может помочь.
    Хотя, если честно, оно того стоило.
    Процесс игры приносил кучу эмоций, хоть и понимал, что за это наказывают.
    Так что вот моя история, чтобы другие знали, что читерство может
    закончиться баном.

Leave a Reply

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