Reputation: 480
I want to replace multiple Newline characters with one Newline character, multiple spaces with a single space and Insert In to database.
so far I tried this
preg_replace("/\n\n+/", "\n", $text);
and doesn't work !
I also do this job on the $text for formatting.
$text = wordwrap($text,120, '<br/>', true);
$text = nl2br($text);
Upvotes: 6
Views: 6025
Reputation: 914
Considering the spaces in the last line.
$text= preg_replace( "/[\r\n]+\s+/", "\r\n", $text );
Upvotes: 1
Reputation: 51
Try to use following:
$text = str_replace(PHP_EOL, '', $text);
Upvotes: 1
Reputation: 368
You probably need this:
preg_replace("/(\s)+/", "$1", $input_lines);
\s --- matches any white space character (all characters like spaces, tabs, new lines, etc)
$1 --- The first white-space char in a set. If the first is a space and the we have 3 new lines after it. We'll get only 1 space.
Alternatively you can use this:
preg_replace("/(\n)+/", "$1", $input_lines);
preg_replace("/( )+/", "$1", $input_lines);
Upvotes: 5
Reputation: 1969
You need to use the correct end of line character depending on the system. PHP_EOL
determines the end of line character for you.
$text = str_replace(PHP_EOL, array("\n", "\r\n", "\r"), $text);
<br />
is for HTML only
Windows uses "\r\n" for new line characters
Unix-based uses "\n"
Mac (I think) uses "\r"
Upvotes: 1
Reputation: 80653
Try using the following pattern:
/[\n\r]+/
as follows:
preg_replace( "/[\r\n]+/", "\n", $text );
Upvotes: 14