1.) To just remove one stopword from start or end of the string by using regex like this:
~^\W*(der|die|das|the)\W+\b|\b\W+(?1)\W*$~i
~
is the pattern delimiter
^
the caret anchor matches start of the string
\W
(upper) is a short for a character, that is not a word character
(der|die|das|the)
alternation |
in first parenthesized group
\b
matches a word boundary
- At
(?1)
the pattern of first group is pasted
$
matches right after the last character in the string
- Used
i
(PCRE_CASELESS) flag. If input is utf-8, also need u
(PCRE_UTF8) flag.
Reference - What does this regex mean
Generate the pattern:
// array containing stopwords
$stopwords = array("der", "die", "das", "the");
// escape the stopword array and implode with pipe
$s = '~^\W*('.implode("|", array_map("preg_quote", $stopwords)).')\W+\b|\b\W+(?1)\W*$~i';
// replace with emptystring
$searchString = preg_replace($s, "", $searchString);
Note that if ~
delimiter occurs in the $stopwords
array, it also has to be escaped with a backslash.
PHP test at eval.in, Regex pattern at regex101
2.) But to remove stop words anywhere in the string how about splitting into words:
// words to be removed
$stopwords = array(
'der' => 1,
'die' => 1,
'das' => 1,
'the' => 1);
# used words as key for better performance
// remove stopwords from string
function strip_stopwords($str = "")
{
global $stopwords;
// 1.) break string into words
// [^-\w\'] matches characters, that are not [0-9a-zA-Z_-']
// if input is unicode/utf-8, the u flag is needed: /pattern/u
$words = preg_split('/[^-\w\']+/', $str, -1, PREG_SPLIT_NO_EMPTY);
// 2.) if we have at least 2 words, remove stopwords
if(count($words) > 1)
{
$words = array_filter($words, function ($w) use (&$stopwords) {
return !isset($stopwords[strtolower($w)]);
# if utf-8: mb_strtolower($w, "utf-8")
});
}
// check if not too much was removed such as "the the" would return empty
if(!empty($words))
return implode(" ", $words);
return $str;
}
See demo at eval.in, ideone.com
// test it
echo strip_stopwords("The Hobbit das foo, der");
Hobbit foo
This solution will also remove any punctuation besides _
-
'
because it's imploding remaining words with space after removing the common words. The idea is to prepare the string for a query.
Both solutions don't modify the case and will leave the string if it only consists of one stopword.
Lists of common words