I’m looking to run through a string and replace just one occurence of each keyword in an array with the linked keyword.
I also want to avoid replacing any keywords if they appear inside other tags such as <h2>, <h3>, <img>, <a>,<div> etc…
Right now I have: foreach ($keyword_array as $kw=>$kwlink){ $string = preg_replace('@(?<=\W|^)('.$kw.')(?=\W|$)@i', '<a href="'.$kwlink.'">$1</a>', $string, 1); }
So now you finally answered my first question - although none of those apart from <img> should ever appear in a table and an <img> would normally fill an entire cell and if one cell in a col;umn is an image then all the others would be as well.
So if you are processing a column of the table that contains text there wouldn’t be any tags in those cells to ship over. At least not any tags that can contain anything that can be misinterpreted as text.
I really don’t think I’ve made myself clear. So I’ll try again.
Let’s just say I have a string of text that can contain tags such as <h2>, <h3>, <img>, <a>,<div>
I want to search for a set of keywords in this text and replace with my keywords links (just one time for each keyword though). My code in the first post does this just fine
However, the problem I have is that it will find the first instance of a keyword inside e.g. a heading tag:
<h2>....keyword></h2>
I want to skip any first instances of each keyword that my regex finds are inside a tag like this.
Putting together good regex can be difficult for even seasoned coders and can get gnarly fast.
I would consider using one of the DOM parsers to whittle the “haystack” down before looking for the “needles”.
As long as your HTML is structured consistently you should be able to gather up the p tag text content and go from there.
Consider replacing all the tags regardless and then go back and manually remove tags from <h2… $tag …/h2> . I should imagine there will not be a lot of $tags to remove.