开发者

PHP filter string input, cut off all newlines, 1 chars

I'm w开发者_运维知识库riting 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


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


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.


\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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜