Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip specific words from string

Tags:

php

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

like image 403
Yannis Avatar asked Feb 18 '12 14:02

Yannis


2 Answers

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']

like image 106
iDoes Avatar answered Sep 19 '22 13:09

iDoes


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.

like image 36
cmbuckley Avatar answered Sep 18 '22 13:09

cmbuckley