Jump to content

New Lines In Str_replace


DarkElf

Recommended Posts

I'm trying to write a code that takes a txt file and converts it to html whilst retaining formatting. It all works fine except for one little glitch - where there is a double return in the txt file I want to close the html paragraph element and then open a new one (so the paragraph is properly split using the <p></p> tags rather than double <br />'s). For some reason I can't get it to work properly.I've used nl2br() to convert new lines to breaks (<br />). I've then tried using str_replace() to search for instances where there are two <br /> tags immediately after each other, but it doesn't find them. I think the problem relates to the fact that the consecutive tags are on seperate lines, i.e. i'm not look for:<br /><br />I'm looking for:<br /><br />I would have assumed that to find and replace the latter I could use the following code:

<?php$string = file_get_contents(filename.txt);$string = nl2br($string);$string = str_replace("<br />\n<br />","</p>\n<p>,$string);?>

But this doesn't work. What's really confusing me is that if I try simply searching for and replacing the 2nd of the two <br /> tags it works fine:

<?php$string = file_get_contents(filename.txt);$string = nl2br($string);$string = str_replace("\n<br />","</p>\n<p>,$string);?>

The inverse is not true (i.e. it finds "\n<br />" but it doesn't find "<br />\n")On the plus side that last version of code very nearly delivers the desired effect, however it means that there is a redundant <br /> tag at the end of each paragraph that I'd quite like to eliminate.Can anyone explain to me why this happens and how to fix it?

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...