Find and remove words from multiple arrays

Asked

Viewed 485 times

1

I have some arrays that come from the database, and would like to remove word occurrences 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 terms that are in the sentence, based on the variable $bad_words, so case-insensitve, using Regex for this?

2 answers

2


Hello! You can use the function str_ireplace, with it you do the substitution with ignore case. See an example of getting the expected result:

<?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

?>

1

1 - single words example - ideone

Computing the difference of the two arrays with the function array_udiff and without differentiating between upper and lower case 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 - Sequence of words 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

  • Leo, an observation, if the word $bad_words are composed, would not make identification because of the explode. Example, if 'search' was 'looking for some'.

  • @Bruno Rigolon, this is not clear in the question, as it was asked, it is meant to be isolated words. But I will take advantage and edit the answer.

  • I agree Leo, it was just an observation. ;)

  • @Bruno Rigolon of which way was worth because I developed another option :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.