Page 1 of 1

Have a replace function only replace outside of HTML tags

Posted: Sat Jul 31, 2004 1:53 pm
by prov
Alright, I've got a content management software thing going on for my website and I decided to make it so that the software would replace a title of another article with a link to that article:

So, if you had an article named "Margin" and in your article named "Bar" you had:

Code: Select all

"...Make sure your Word Document's margin is within printable range..."
It would change to:

Code: Select all

"...Make sure your Word Document's <a href="showarticle.php?title=margin">margin</a> is within printable range..."
So far, it worked fine, until, for whatever reason, I overlooked the obvious flaw where if you had "margin" in one of your HTML tags, it would put the a tag inside of that tag.

Code: Select all

"<div style="margin: 0px; ">Hello World!</div>"
Would turn into:

Code: Select all

"<div style="<a href="showarticle.php?title=margin">margin</a>: 0px; ">Hello World!</div>"
"Well, that's a stupid thing I did," I thought to myself. I figured it would be a bit easy to fix... just set a regular expression replace up, and then work it that way... I'm very poor with regex as it was, but I finally realized it was not that easy, since it would replace the entire document with one big "A" tag.

Next, I thought it would be best to explode the document by the "<" character, and then use a sub string for each array, so that it would only replace the needles after the ">" character. It would be a kind of "sloppy" code, but might do the trick. That returned a fatal memory error.

I've tried other methods, but they either made the loadtime too long, or simply didn't work.

Is there some kind of easy way to make this thing work the way I want it?

Posted: Sat Jul 31, 2004 2:12 pm
by feyd
untested

Code: Select all

preg_replace('#(>.*?)margin(.*?<)#i','$1<div style whatever>$2',$data)

Posted: Mon Aug 02, 2004 12:36 pm
by prov
Yours almost worked. I needed to make a few changes, though. You led me in the right direction, though. :) Thanks.