views:

76

answers:

2

Hello, I want to clean up some parsed text such as

\n the said \r\n\r\n\r\n I look in your eyes my dear\r\n\r\nI see green rolling Forests\r\n\r\nI see the far away Sky\r\n\r\nThey turn into the rain\r\n\r\n\r\nI see high soaring eagles... more\n

So I want to get rid of the "\n", "\r\n", "\r\n\r\n", "\r\n\r\n\r\n", "\r\n\r\n\r\n\r\n" and "\r". That's all the combinations that appear in my parsed text.

Is there a way to do this in php?

+1  A: 

What about

$text = str_replace(array("\n", "\r"), '', $text);

That will remove all new line characters.

If you want them as new lines, I'd change the replace to <br /> for HTML (or better still, use PHP's nl2br()), or standardise them in normal text with \n, for example.

alex
or just use the built in nl2br ( http://php.net/manual/en/function.nl2br.php )
Jonathan Fingland
Oh yeah - that one completely slipped my mind.
alex
Works perfectly, couldn't have hoped for better. Thanks!
David Willis
+2  A: 

If you just want 1 newline instead of multiple I would suggest this:

$clean = preg_replace(array("/\r+/","/(\n){2,}/"),array("","\n"),$text);

Otherwise str_replace to strip out newlines or nl2br will do the job. You could also adapt the regex to replace 1 or more newlines with a BR tag:

$clean = preg_replace(array("/\r+/","/\n+/"),array("","<br />"),$text);
Tim