[ACCEPTED]-Strip specific words from string-php

Accepted answer
Score: 22

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.


Score: 7

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

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

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

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

I hope this helps.

Score: 1


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


Score: 1

I had the same problem and fixed it like 1 this:

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

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

Score: 0
$areaname = str_replace(array("to", "the","a","an","in","by","but","are","is","had","have","has"),'',$areaname);

i used it for this and works fine

but it 3 will add spaces in place of these words,so 2 you need to use replace again to chk double 1 spaces and remove them

Score: 0

If you are using utf-8 characters you will 2 need to add /u to the regex expression

$string = "regadío";
$omit = ["a", "y", "o"];
$string = preg_replace('/\b(' . implode('|', $omit) . ')\b/u', '', $string);

Without 1 the /u it will remove the "o" from "regadío" -> "regadí"

More Related questions