Sjoerd Maessen blog

PHP and webdevelopment

Limit the number of newlines in a string

with one comment

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:

  1.  
  2. /**
  3.  * limitBreaks, prevents texts with a lot of enters/breaks after each other
  4.  *
  5.  * @param string $sText
  6.  * @param int $iAmount default 2, numbers of newlines that may occur after eachother
  7.  * @return string, cleaned up string with limited number of newlines
  8.  */
  9. function limitBreaks($sText, $iAmount=2)
  10. {
  11.         return preg_replace("/[\r\n]{".($iAmount+1).",}\t*[\r\n]*/", str_repeat(PHP_EOL, $iAmount), $sText);
  12. }
  13.  

As you can see a simple but effective function.

  • Share/Bookmark

Written by Sjoerd Maessen

January 28th, 2010 at 10:44 pm

Posted in Regexp

Tagged with , , ,

One Response to 'Limit the number of newlines in a string'

Subscribe to comments with RSS or TrackBack to 'Limit the number of newlines in a string'.

  1. NiksTemi 7 Prompt, where to me to learn more about it?

    _____________
    cialas
    work
    7

    ikoFent

    26 Aug 10 at 11:01 am

Leave a Reply