[PHP] Replacing exact words

5 replies
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
googler
yahoos
into
go*gler
yah*os

please help how to make it only replacing exact words?
GBU for all that answering
#exact #php #replacing #words
  • Profile picture of the author softwarewarden
    PHP Code:
    $word = array(
    ' google ',
    ' yahoo '
    );

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

    $this->post['message'] = str_ireplace($word$link$this->post['message']); 
    {{ DiscussionBoard.errors[10075419].message }}
  • Profile picture of the author Nathan K
    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
    {{ DiscussionBoard.errors[10075628].message }}
  • Profile picture of the author basketmen
    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?
    {{ DiscussionBoard.errors[10076431].message }}
  • Profile picture of the author basketmen
    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?
    {{ DiscussionBoard.errors[10076438].message }}
  • Profile picture of the author Nathan K
    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.
    {{ DiscussionBoard.errors[10076468].message }}

Trending Topics