Reputation: 922
I want to strip whole words from a string wherever they are inside the string.
I have created an array of forbidden words:
$wordlist = array("or", "and", "where", ...)
Now I strip the words:
foreach($wordlist as $word)
$string = str_replace($word, "", $string);
The problem is that the above code also strips words that contain the forbidden words like "sand" or "more".
Upvotes: 15
Views: 33874
Reputation: 509
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']
Upvotes: 1
Reputation: 56
If you are using utf-8 characters you will 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 the /u it will remove the "o" from "regadío" -> "regadí"
Upvotes: 0
Reputation: 7
$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 will add spaces in place of these words,so you need to use replace again to chk double spaces and remove them
Upvotes: 0
Reputation: 682
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.
Upvotes: 8
Reputation: 42537
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.
Upvotes: 22