Reputation: 379
How to replace or filter bad words from text like str_ireplace? I need replace the word from key to value in array but without use foreach and explode.
Example array
$_filter = [
'badwords' => [
'one' => 'time',
'bad' => 'good',
'ugly' => 'beauty'
]
];
Example replace
$before = 'anyone help me please';
$after = 'anytime help me please';
$before = 'I need BaD function';
$after = 'I need good function';
$before = 'I am so (ugly)';
$after = 'I am so (beauty)';
trying these but not working. Anyone can help me please. Thank you
Upvotes: 2
Views: 343
Reputation: 424
The function str_ireplace() will accept arrays as the first, second and third parameter according to its documentation:
http://php.net/manual/en/function.str-ireplace.php
Using the function array_keys(), you can get all the keys from your filter array to pass them as the first parameter. Then you'll just have to pass the array as the second parameter, and the string as the third parameter.
Code example:
$filter = [
'badwords' => [
'one' => 'time',
'bad' => 'good',
'ugly' => 'beauty'
]
];
$before = 'anyone help me please';
$after = str_ireplace(array_keys($filter['badwords']), $filter['badwords'], $before);
echo $after;
And your output will be:
anytime help me please
Upvotes: 3
Reputation: 11320
I would use a simple str_replace
<?php
$search = array('one', 'bad', 'ugly');
$replace = array('time', 'good', 'beauty');
$before = 'anyone help me please';
echo str_replace($search, $replace, $before);
$before = 'I need bad function';
echo str_replace($search, $replace, $before);
$before = 'I am so (ugly)';
echo str_replace($search, $replace, $before);
Here's the Eval
Upvotes: 0