English 中文(简体)
PHP filter string input, cut off all newlines, 1 chars
原标题:

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

最佳回答

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

$lines = explode("
", str_replace(array("
", "
"), "
", $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( /^.?$
/m ,   , $string);
问题回答

How about this:

$str = str_replace(array("
", "
"),   , $str);

Where $str is your user input.

EDIT:

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

is a valid input for a newline, as well as and . Run a Regex or str_replace to replace all combinations of and with and you can use use explode(" ", $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( "(
?
)+" , "
", $empty_lines);




相关问题
CSS working only in Firefox

I am trying to create a search text-field like on the Apple website. The HTML looks like this: <div class="frm-search"> <div> <input class="btn" type="image" src="http://www....

image changed but appears the same in browser

I m writing a php script to crop an image. The script overwrites the old image with the new one, but when I reload the page (which is supposed to pickup the new image) I still see the old one. ...

Firefox background image horizontal centering oddity

I am building some basic HTML code for a CMS. One of the page-related options in the CMS is "background image" and "stretch page width / height to background image width / height." so that with large ...

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签