Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse String - remove some words from string [duplicate]

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

like image 473
behz4d Avatar asked Jun 10 '26 14:06

behz4d


2 Answers

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.

like image 61
hakre Avatar answered Jun 13 '26 07:06

hakre


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);
like image 45
dfsq Avatar answered Jun 13 '26 06:06

dfsq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!