Forum Moderators: coopster

Message Too Old, No Replies

How to preserve newline when preg_replace?

         

thedealmaker

5:08 pm on Feb 1, 2006 (gmt 0)

10+ Year Member



Hi,
I am trying to do the following without removing the newline. But somehow, it always remove the new line. How do I preserve the newline? Many thanks.

// remove extra space in middle, remove all space at front & end, replace tab with space, remove null, remove vertical tab, remove extra space between double quote and non-space characters

$data = "hello\n\"morning";
$pattern = array("/\s+/", "/^\s+/", "/\s+$/", "/\t/", "/\x0B/", "/\s+\"/", "/\"\s+/");
$replace = array(' ', '', '', ' ', '', "\"", "\"");
$data = preg_replace($pattern, $replace, $data);

Salsa

5:24 pm on Feb 1, 2006 (gmt 0)

10+ Year Member



I think that \n (new line) is a preg \s character, so you're removing it with your preg_replace. Just try adding a \n onto the end of $replace.

Anyango

10:44 am on Feb 2, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



or

$data = "hello\n\"morning";
$data=str_replace("\n","<newline>",$data);
$pattern = array("/\s+/", "/^\s+/", "/\s+$/", "/\t/", "/\x0B/", "/\s+\"/", "/\"\s+/");
$replace = array(' ', '', '', ' ', '', "\"", "\"");
$data = preg_replace($pattern, $replace, $data);
$data=str_replace("<newline>","\n",$data);

;)