Regular expression help

Discussion in 'PHP' started by pluswebdev, Aug 16, 2008.

  1. #1
    Hi,
    can someone help me to write the right regular expression for the following.

    Let we have the folowing text sourse
    
    This is example text with keyword and 
    also <a href="http://www.somekeyword.com">linking page</a> and so on..
    
    Code (markup):
    I want the keyword "keyword" to be replaced with "<b>keyword</b>"

    We I use the following:
    
    $text = // the text source above
    $text = preg_replace('/keyword/i', '<b>\\0</b>', $text);
    
    PHP:
    it returns
    
    This is example text with <b>keyword</b> and 
    also <a href="http://www.some<b>keyword</b>.com">linking page</a> and so on..
    
    Code (markup):
    I want the "keyword" in the url NOT to be replaced.

    Any advice how can do this?
     
    pluswebdev, Aug 16, 2008 IP
  2. shivakhanal

    shivakhanal Peon

    Messages:
    13
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Please Use This this may work according to your requirement.

    <?php
    $text = 'This is example text with keyword and also <a href="http://www.somekeyword.com">linking page</a> and so on..';// the text source above
    $text = preg_replace('/ keyword /i', '<b>\\0</b>', $text);
    echo $text;
    ?>
     
    shivakhanal, Aug 17, 2008 IP
  3. pluswebdev

    pluswebdev Banned

    Messages:
    205
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #3
    @shivakhanal thanks but your solution not helps me if we have for example 'somekeywod' not in the URL
     
    pluswebdev, Aug 17, 2008 IP
  4. guzz

    guzz Guest

    Messages:
    25
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    please try this
    
    <?
    $text = // the text source above
    $text = preg_replace("#(^[<a])+(.+?)keyword#si"', '<b>\\0</b>', $text);
    ?>
    
    PHP:
    i dont try code but i think it will work
    explain is:
    ^[<a] = not start with <a
     
    guzz, Aug 17, 2008 IP