Forum Moderators: coopster

Message Too Old, No Replies

str replace on r\n\ not working

         

internetheaven

5:06 pm on Aug 17, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'm trying to create an article formatter to speed up moving newly written pieces from Word format to txt format for upload. I've got this:

<?php
$article = file_get_contents("http://www.example.com/article.txt");
$article = str_replace("‘","'", $article);
$article = str_replace("’","'", $article);
$article = str_replace('“','"', $article);
$article = str_replace('”','"', $article);
$article = str_replace(" – "," - ", $article);
$article = str_replace("£","&pound;", $article);
$article = str_replace("&","&amp;", $article);
$article = str_replace("\r\n","<br>", $article);
echo $article;
?>

but none of the \r\n's change to <br>s.

What have I got wrong?

Thanks
Mike
P.S. what would be best is an online textarea where I can enter the article, click submit and the new formatted article shows up -- but I don't know how to set that up so I'm using file_get_contents to pull the article from a file I'm using on the server.

brotherhood of LAN

5:16 pm on Aug 17, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Have you tried replacing \n on its own?

$article = preg_replace("'\r?\n'","<br>", $article);

Alternatively, the above snippet would replace either \r\n or \n

CyBerAliEn

5:21 pm on Aug 17, 2009 (gmt 0)

10+ Year Member



Try the following:

$article = nl2br($article,false);

Instead of doing the str_replace for new lines. It will interject HTML break tags where new lines are found. This of course is using the UNIX '\n' line breaks.

For a more "OS-free" solution, the following is a decent solution:

$article = str_replace(array("\r\n","\r","\n"), "<br>",$article);

The 2nd one should work no matter what, and no matter what system the file came from. If this doesn't work either... check your file?