6

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);
3
  • You probably should take into account the different possible newline combinations, i.e. \n, \r or \r\n. It depends on the system you are running this on. Commented Aug 4, 2014 at 10:18
  • what is the difference between each combination ? I am using MAC OS. Commented Aug 4, 2014 at 10:21
  • For reference I believe Windows uses \r\n, Linux and Unix like systems tend to use \n and Mac OS tends to go for \r. You should really write your code to take into account all cases though. You should try to aim for platform independence where possible. Commented Aug 4, 2014 at 11:44

6 Answers 6

14

Try using the following pattern:

/[\n\r]+/

as follows:

preg_replace( "/[\r\n]+/", "\n", $text );
Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

1

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"

Comments

1

Try to use following:

$text = str_replace(PHP_EOL, '', $text);

Comments

1

Considering the spaces in the last line. $text= preg_replace( "/[\r\n]+\s+/", "\r\n", $text );

Comments

0

try preg_replace() :

preg_replace("/[\r\n]+/", "\n", $text);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.