Strip specific words from string

I had the same problem and fixed it like this:

$filterWords = ['a','the','for'];
$searchQuery = 'a lovely day';
$queryArray = explode(' ', $searchQuery);
$filteredQuery = array_diff($queryArray, $filterWords);

$filteredQuery will contain ['lovely','day']


For this you can use preg_replace and word boundaries:

$wordlist = array("or", "and", "where");

foreach ($wordlist as &$word) {
    $word = '/\b' . preg_quote($word, '/') . '\b/';
}

$string = preg_replace($wordlist, '', $string);

EDIT: Example.


TRY:

 $string = preg_replace("\b$word\b", "", $string);

The str_replace also supports the input of an array. This means that you could use it in the following way:

str_replace(array("word1", "word2"), "", $string);

This means that all the words existing in the array will be replaced by an empty string. If you want specific replacements you can create an array of replacements as well.

To remove the correct words in your setup I would advise to add spaces around " or " and " where ". As you would only remove the real words and not parts of words.

I hope this helps.

Tags:

Php