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".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With