Jump to content

any way to restrict the number of new lines \r\n ?


Anti-Moronic

Recommended Posts

Hi, I have a problem at the moment where some problem users are taking advantage of the new line in the text area...they are submitting text with 100 new lines and obviously the page is stretching forever.

 

Is there any way of using nl2br but only converting a certain amount of new lines? like only the first 10?

 

Appreciate any insight.

Link to comment
Share on other sites

Here is one way to do it, basically if 10 blank lines are reached nothing is appended to the string until that variable is reset (meaning non-empty data was output).

 

<?php
$string = "somtext\r\nmore text\r\n\r\n\r\n\r\nmore text\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nmoretext here\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n";
$strArr = explode("\r\n", $string);

$string = "";
$i=1;
foreach ($strArr as $str) {
if (!empty($str)) {
	$string .= $str;	

	// reset $i
	$i=1;
}else {
	if ($i < 10) {
		$string .= "\r\n";
		$i++;
	}
}
}
echo nl2br($string) . "end";
?>

Link to comment
Share on other sites

Thanks guys appreciate the help. I should clarify too.

 

What I meant was to only parse up to a number of new lines in total. Thanks premiso, that will help if users persist on new lines with no data in between.

 

I'm thinking what would be ideal is to use preg_replace with an offset and remove any \r\n after the limit (say 10). Then I can safely use nl2br as needed.

 

Thanks again.

Link to comment
Share on other sites

I'm not really good with regex, but how about something like:

preg_replace('#${10,}#',"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n",$textarea);

 

It can probably be written better, but should do the job... I think...

 

[edit]

 

Oh well... compilation error...

 

[edit]

 

Silly me.

 

preg_replace('#(\r\n|\r|\n){10,}#',"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n",$textarea);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.