Strip specific words from string

php

Solution

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.

Problem

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".

Original source