[SOLVED] Have a replace function only replace outside of HTM

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
prov
Forum Newbie
Posts: 10
Joined: Thu Mar 25, 2004 9:13 pm
Location: Providence, RI
Contact:

Have a replace function only replace outside of HTML tags

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

untested

Code: Select all

preg_replace('#(>.*?)margin(.*?<)#i','$1<div style whatever>$2',$data)
prov
Forum Newbie
Posts: 10
Joined: Thu Mar 25, 2004 9:13 pm
Location: Providence, RI
Contact:

Post by prov »

Yours almost worked. I needed to make a few changes, though. You led me in the right direction, though. :) Thanks.
Post Reply