DarkElf Posted December 31, 2008 Share Posted December 31, 2008 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 More sharing options...
redwall_hp Posted December 31, 2008 Share Posted December 31, 2008 Try this: <?php$string = file_get_contents(filename.txt);$string = nl2br($string);$string = str_replace("<br />\r\n<br />","</p>\n<p>,$string);?> There might be a carriage return as well as a newline in there. Link to comment Share on other sites More sharing options...
DarkElf Posted January 2, 2009 Author Share Posted January 2, 2009 Nope, already tried that The str_replace function doesn't seem to like patterns which run across multiple lines. I can't understand why, the \n character seems to have some special rules applied to it that make it behave funny. Link to comment Share on other sites More sharing options...
Wander Posted January 2, 2009 Share Posted January 2, 2009 try using preg_replace instead, $str = preg_replace('/<br ?\/?>\r?\n<br ?\/?>/i',"</p>\n<p>",$str); Link to comment Share on other sites More sharing options...
DarkElf Posted January 6, 2009 Author Share Posted January 6, 2009 try using preg_replace instead, $str = preg_replace('/<br ?\/?>\r?\n<br ?\/?>/i',"</p>\n<p>",$str);Works a charm, thanks Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.