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.

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";
?>

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.

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);

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.