Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

replacing spaces with newline

11 views
Skip to first unread message

Simon Hall

unread,
May 4, 2013, 7:09:06 AM5/4/13
to
Hi Guys,

I am new to PHP and I am trying to clean up some text, what I am looking to do is to create a new line at each space, I have tried the following but it still outputs with just spaces.

<?php

$file = file_get_contents("mytext.txt");

$file = Str_replace(" ", "\r\n", $file);

echo $file;

?>

Any ideas?


Cheers


Simon

Denis McMahon

unread,
May 4, 2013, 8:14:13 AM5/4/13
to
On Sat, 04 May 2013 04:09:06 -0700, Simon Hall wrote:

> $file = Str_replace(" ", "\r\n", $file);

Last time I checked, it was str_replace, not Str_replace. You don't need
the \r on all operating systems. Some operating systems that I understand
may require the \r may also use 0xa0 instead of 0x20 for a space under
some circumstances.

--
Denis McMahon, denismf...@gmail.com

bill

unread,
May 4, 2013, 8:20:38 AM5/4/13
to
When displaying in a browser multiple spaces/tabs/newlines are
all rendered as 1 space. If you want the _display_ to treat
spaces as newlines use the html line break:
$file = Str_replace(" ", <br />", $file);
or keep what you have and use

$file = nl2br($file)

http://us2.php.net/manual/en/function.nl2br.php

bill

Jeff North

unread,
May 4, 2013, 8:24:57 AM5/4/13
to
On Sat, 4 May 2013 04:09:06 -0700 (PDT), in comp.lang.php Simon Hall
<hall.s...@gmail.com>
If you are outputting to html then the \r\n are ignored so you could
use: echo nl2br( $file );

Simon Hall

unread,
May 4, 2013, 10:43:07 AM5/4/13
to
Thanks guys, it was going to be going to a text file anyway. Was me just being an idiot the output was correctly formatted in a text file rather than the output of echo in the webpage.

Thank you for the responses, we live and learn :)
0 new messages