I have a string like:
$text = 'Hello this is my string and texts';
I've got some not allowed words in array:
$filtered_words = array(
'string',
'text'
);
I want to replace all the filtered words in my $text with ***, so I wrote:
$text_array = explode(' ', $text);
foreach($text_array as $key => $value){
if(in_array($text_array[$key], $filtered_words)){
$text = str_replace($text_array[$key], '***', $text);
}
}
echo $text;
The Output:
Hello this is my *** and texts
But I need function to also replace texts with *** since it's also contain a filtered word(text).
How I could achieve this?
Thanks
You can just do it right away, str_replace supports to replace from an array into a single string:
$text = 'Hello this is my string and texts';
$filtered_words = array(
'string',
'texts',
'text',
);
$zap = '***';
$filtered_text = str_replace($filtered_words, $zap, $text);
echo $filtered_text;
Output (Demo):
Hello this is my *** and ***
Take care you have the largest words first and keep in mind when str_replace is in that mode, it will do one replacement after the other - like in your loop. So shorter words - if earlier - could be part of larger words.
If you need something more failsafe you must consider doing a textual analysis first. That could also tell you if you didn't know about words you might want to replace but you didn't thought of so far.
str_replace can accept an array as first parameter. So no need of any for each loop at all:
$filtered_words = array(
'string',
'text'
);
$text = str_replace($filtered_words, '***', $text);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With