views:

468

answers:

4

I'm writing in PHP!

There's a user string input, and I want to cut off all newlines,1 chars that are more than 1 in a row (avoid <br /><br />...).

example:

I am a




SPaMmEr!

would become:

I am a
SPaMmEr!

or

I am a
.
.
.
.
SPaMmEr!

likewise

A: 

How about this:

$str = str_replace(array("\n", "\r"), '', $str);

Where $str is your user input.

EDIT:

Sorry, this code will remove all lines regardless, still might come in handy.

ILMV
A: 

\n is a valid input for a newline, as well as \r\n and \n\r. Run a Regex or str_replace to replace all combinations of \r and \n with \n and you can use use explode("\n", $string), and check all items of the array for one char or empty one. You can remove those, or replace it by a single instance of the repeated char, e.g. I use a single newline for a new paragraph, so it would destroy such.

Femaref
A: 

Why not use regexp for this:

## replace 1 or more new line symbols with single new line symbol
$empty_lines_trimmed = preg_replace('"(\r?\n)+"', "\n", $empty_lines);
Ivan Nevostruev
+2  A: 

Getting all lines is done this way (if you want to catch dos, mac and unix line feeds):

$lines = explode("\n", str_replace(array("\r\n", "\r"), "\n", $string));

Filtering lines with more than one character can be done with preg_grep():

$lines = preg_grep('/^.{2}/', $lines);

Or using regular expressions for the complete process:

preg_match_all('/^.{2}.*$/', $string, $matches);
$lines = $matches[0];

Or if you don't need an array containing all remaining lines, you can remove the unwanted strings with a single call:

$string = preg_replace('/^.?$\n/m', '', $string);
soulmerge
thank you very much, i'll use it!
sombe