Warrior Forum - The #1 Digital Marketing Forum & Marketplace

Warrior Forum - The #1 Digital Marketing Forum & Marketplace (https://www.warriorforum.com/)
-   Programming (https://www.warriorforum.com/programming/)
-   -   [PHP] Replacing exact words (https://www.warriorforum.com/programming/1077028-php-replacing-exact-words.html)

basketmen 22nd May 2015 05:52 PM

[PHP] Replacing exact words
 
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
Quote:

googler
yahoos
into
Quote:

go*gler
yah*os

please help how to make it only replacing exact words?
GBU for all that answering

softwarewarden 22nd May 2015 10:51 PM

Re: [PHP] Replacing exact words
 
PHP Code:

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

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

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


Nathan K 23rd May 2015 03:52 AM

Re: [PHP] Replacing exact words
 
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; 


basketmen 23rd May 2015 03:32 PM

Re: [PHP] Replacing exact words
 
thank you Nathan for replying, already tried like this, but its get error like this

PHP Code:

Parse error: syntax error, unexpected T_FUNCTION in /home/username/public_html/file.php(296) : eval()'d code on line 16 

any other i can try?

basketmen 23rd May 2015 03:36 PM

Re: [PHP] Replacing exact words
 
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?

Nathan K 23rd May 2015 04:12 PM

Re: [PHP] Replacing exact words
 
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.


All times are GMT -6. The time now is 02:45 AM.