![]() |
Need help with a little algorithm thing.
Well, here's my dilemma. I'm kind of new to PHP, although I've done a lot of simple stuff with it.
I'm trying to go through a string, let's call it $str, and replace every occurrence of a newline (\n) with "<p />". However (and this is what makes it difficult) I don't want to perform the replacement if the \n falls between <pre> and </pre> tags. I've tried to accomplish this with a bit of looping, but to no avail. Can anyone here help me on this? Thanks a bunch guys. :D |
For replacement you can use the function str_replace()
For instance: str_replace ("\n", "<p />", $str); The other half is slightly more tricky as there are lots of ways of doing it. I'll show one later, it's late *_* |
not-so-pseudo-code, no guarantees as to correctness
:
$insidePre = false; |
Another similar approach I've used is to take the text as one huge string and break it into lines. You can then use the pre tags to indicate those sections in which you replace newlines (or crlf, or whatever your format has) with <p/> (they're all at the end of the line, of course). When I used it, I actually substituted <p>s and </p>s at the appropriate points. You'll note that except for the beginning and end, and inside <pre> tags, the paragraph breaks come as a </p><p> pair.
|
Jimbo: Yeah, I was having a bit of trouble getting that to work. I changed yours around a bit, but to no avail.
:
function format($theString)DaWei: I'm afraid I don't quite understand. |
You should be using <br/> instead of an empty <p>.
|
Unfortunately using <br /> screws up the tables, so I have to use <p />
|
Try this and see how it works. I did a quick test and I think it was working properly:
:
function format($theString)And, as DaWei mentioned, you might consider changing the logic to pair the tags properly. If you do, you'll need a little extra logic for closing the last tag but not opening a new one. |
Thanks guys. That worked beautifully Jimbo. :)
<3 |
Quote:
Forget all the looping and complicated stuff. There is a 1 line solution: :
echo preg_replace('/(?!((<pre.*?)))\n(?!(([^>]*?<\/pre>)))/', '<p/>', $str);This will replace all occurrences of \n of <p/>, but not if the \n falls in between a pair of <pre></pre> tags. - Sean |
| All times are GMT -5. The time now is 1:24 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC