Regex replace doesn't catch nesting properly.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mlaw40
    New Member
    • Jun 2007
    • 1

    #1

    Regex replace doesn't catch nesting properly.

    I am building a CMS driven website in php and I have a list of terms that for each page content I need to search for and replace with the following code:

    <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.

    [CODE=php]$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($h tml_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_attemp t3 = '/(?(?=('.$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($p attern, $replace_string , $html_body);
    }

    return $html_body;
    }//end function
    [/CODE]
    The results I am looking for when the function returns $html_body is:

    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_furnitur e">hire garden furniture</a> - this would be ignored

    Any help with this would be greatly appreciated.

    Many thanks.
    Last edited by pbmods; Jun 8 '07, 10:43 AM. Reason: Changed code language. Thanks for using CODE tags!
  • pbmods
    Recognized Expert Expert
    • Apr 2007
    • 5821

    #2
    Changed thread title to better describe the problem (and to remove annoying 'please help').

    Heya, mlaw40. Welcome to TSDN!

    Try explodeing your string by '</a>'.

    Comment

    Working...