1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Replacing exact words

Discussion in 'PHP' started by basketmen, May 22, 2015.

  1. #1
    Hi guys, below are simple replacing script a word in to another word, or censorship

    $word = array(
    'google',
    'yahoo'
    );
    
    $link = array(
    'go*gle',
    'yah*o'
    );
    
    $this->post['message'] = str_ireplace($word, $link, $this->post['message']);
    PHP:

    the problem its currently also replacing another words like
    into
    please help how to make it only replacing exact words?
    GBU for all that answering
     
    basketmen, May 22, 2015 IP
  2. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #2
    Preg_replace along with the word boundary should do the trick:

    
    <?php
    $string = 'google yahoo test yahoo';
    $find = array('/\bgoogle\b/', '/\byahoo\b/');
    $replace = array('go*gle', 'yaho*');
    echo preg_replace($find, $replace, $string);
    
    PHP:
     
    ThePHPMaster, May 22, 2015 IP
  3. basketmen

    basketmen Well-Known Member

    Messages:
    837
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    130
    #3
    thank you for replying
    where i need to put $this->post['message'] btw?
     
    basketmen, May 23, 2015 IP
  4. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #4
    That would take place instead of the original string and takes the results of preg_replace instead of outputting it.
     
    ThePHPMaster, May 23, 2015 IP