Find and remove words from multiple arrays

2

I have some arrays that come from the database, and I would like to remove occurrences of words in them, for example, the string in $title

$title = "Eles foram com José procurar alguma coisa";

$bad_words = array('foram','prOcuRar','.....');

How can I remove all the terms that are in the sentence, based on the $bad_words variable, in case-insensitve , using Regex for this?

    
asked by anonymous 11.06.2017 / 01:27

2 answers

2

Hello! You can use the str_ireplace function, with which you do the substitution with ignore case. Here is an example of getting the result you expect:

<?php

$bad_words = array('foram','prOcuRar','.....');
$title = "Eles foram com José procurar alguma coisa";

foreach($bad_words as $bad_word)
{
    $title = str_ireplace($bad_word, '', $title);
}

print_r($title); //Eles com José alguma coisa

?>
    
11.06.2017 / 01:45
1
  

1 - isolated words example - ideone

Computing the difference of the two arrays with the array_udiff function and not case-sensitive with strcasecmp

$bad_words = array('foram','prOcuRar','.....');
$title = "Eles foram com NGTHM4R3 procurar alguma coisa para remover ocorrências de palavras";

$title = implode(" ", array_udiff(explode(" ", $title), $bad_words, 'strcasecmp'));

print_r($title);
  

2 - Word sequences example - ideone

$bad_words = array('foram','prOcuRar alguma coisa','alguma','Ponte que partiu');
$title = "Eles foram com NGTHM4R3 procurar alguma coisa pedir ajuda para remover palavras ou sequência de palavras tal como Ponte que partiu";

$title = str_ireplace($bad_words,'',$title);
$title= preg_replace('/\s(?=\s)/', '', $title);

echo $title;

DOCS:

array_udiff

strcasecmp

str_ireplace

    
11.06.2017 / 02:48