Replace keywords in HTML using regular expression

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
astroCoder
Forum Newbie
Posts: 1
Joined: Tue May 12, 2009 4:14 am

Replace keywords in HTML using regular expression

Post 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;
 
?>
 
Last edited by Benjamin on Tue May 12, 2009 11:26 am, edited 1 time in total.
Reason: Added [code=php] tags.
Post Reply