<a href="[link]">[term]</a>
The problem I have is that a term can appear in another term, for example garden furniture, hire garden furniture. When I am doing a basic preg_replace it means that the term hire garden furniture has a nested link tag because it is found for both terms. What I need to do is ignore any term that ends with </a> so that they only get replaced once. The function I am using is below and I have commented the parts that don't seem to be working correctly.
Expand|Select|Wrap|Line Numbers
- $html_body = "We have a wide variety of garden furniture for any occasion. You can hire garden furniture from us for use at parties, corporate functions etc.";
- private function _replaceText($html_body)
- {
- $terms = array("hire garden furniture", "garden furniture", "office furniture");
- foreach($terms as $t)
- {
- $replace_string = '$1';
- $pattern attempt1 = '/('.$row['term'].')/i'; //This replaces all the terms with $replace_string above but hire garden furniture results in a nested link
- $pattern attempt2 = '/('.$row['term'].'[^()])/i'; //This does not replace anything and the content is returned as it was
- $pattern_attempt3 = '/(?(?=('.$row['term'].'<........a>))(notmatch)|(('.$row['term'].')))/i'; //This replaces the terms but does not recognise $1 in the replace_string and still results in a nested link
- $html_body = preg_replace($pattern, $replace_string, $html_body);
- }
- return $html_body;
- }//end function
We have a wide variety of <a href="[link]">garden furniture</a> for any occasion. You can <a href="[link]">hire garden furniture</A> from us for use at parties, corporate functions etc.
In a nutshell I am looking for a pattern that only replaces a given term if its is not already within a link tag, for example:
Hire garden furniture - this would be replaced
<a href="/garden_furniture">hire garden furniture</a> - this would be ignored
Any help with this would be greatly appreciated.
Many thanks.