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_replacesupports to replace from an array into a single string:Output (Demo):
Take care you have the largest words first and keep in mind when
str_replaceis 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.