Page 1 of 1

Replace keywords in HTML using regular expression

Posted: Tue May 12, 2009 4:22 am
by astroCoder
Hello everyone,

I'm having a hard time replacing several keywords (found in an array) in an html page into links with a given url, again stored in a 2d array. In fact I want to replace every matched keyword which is not a link and which is not found in a tag. Below is my code so far, can't someone please help me out with this. Thanking you in advance,

Code: Select all

 
<?php
include('../simple_html_dom.php');
$html = file_get_html('test.html');
$pattern = '#(^|>)[^<]+#';
 
    function replacement($textChunk)
    {
        //$keywords = array('#\bkeyword1\b#i','#\bkeyword2\b#i');
        $keywords = array( 
                    array ("#\bkeyword1\b#i", " <a href=\"keyword1.html\" >keyword1</a> "),
                    array ("#\bkeyword2\b#i", " <a href=\"keyword2.html\" >keyword2</a> ")
                 );
        
        return preg_replace($keywords, '<a href=\"url here\">\0</a>', $textChunk[0]);
    }
    
    $text = preg_replace_callback($pattern, 'replacement', $html);
    echo $text;
 
?>