[PHP] Replacing exact words

by 5 replies
6
Hi guys, below are simple replacing script a word in to another word, or censorship

PHP Code:
$word = array(
'google',
'yahoo'
);

$link = array(
'go*gle',
'yah*o'
);

$this->post['message'] = str_ireplace($word$link$this->post['message']); 

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
#programming #exact #php #replacing #words
  • PHP Code:
    $word = array(
    ' google ',
    ' yahoo '
    );

    $link = array(
    ' go*gle ',
    ' yah*o '
    );

    $this->post['message'] = str_ireplace($word$link$this->post['message']); 
  • PHP Code:
    $message 'google yahoo,  googler yahoos';

    $word = array(
    'google',
    'yahoo'
    );

    $link = array(
    'go*gle',
    'yah*o'
    );


    $combine array_combine($word$link);

    $callback = function($match) use ($combine){
        return 
    $combine[$match[1]];
    };

    $exp '/\b('implode('|'$word).')\b/';

    $message preg_replace_callback($exp$callback$message);

    echo 
    $message
  • thank you Nathan for replying, already tried like this, but its get error like this

    PHP Code:
    Parse errorsyntax errorunexpected T_FUNCTION in /home/username/public_html/file.php(296) : eval()'d code on line 16 
    any other i can try?
  • thank you for replying softwarewarden, its works if the words in the middle of text, its simple way, but not works if the words in the front or back, like this

    PHP Code:
    googleg*oglegoogle
    yahooyah
    *oyahoo 
    any other code please?
  • The reason it did not work is because of your php version. try this
    PHP Code:
    $message 'google yahoo,  googler googleyahoosgoogle';

    $word = array(
    'google',
    'yahoo'
    );

    $link = array(
    'go*gle',
    'yah*o'
    );

    $combine array_combine($word$link);

    $exp '/\b('implode('|'$word).')\b/';

    $message preg_replace_callback($exp, function($match) use ($combine){
        return 
    $combine[$match[1]];
    }, 
    $message);

    echo 
    $message
    I dont think this is possible

    googleg*oglegoogle
    yahooyah*oyahoo

    Because your first requirement is not to replace words like "googler" and in your second requirement is replace words like "googler".

    If you want to replace all the words remove the two '\b's in $exp.

Next Topics on Trending Feed