I've been instructed to write a routine that strips certain words from a text string. I concocted this function but I'm having trouble dealing with word delimiters correctly because the words may occur at the beginning of the string (in which case i want NO delimiters to remain) or the word may occur between two other words (in which case I want to leave one delimiter.
I was wondering if this might be possible with only one preg_match statement or whether I'll have to get all fancy with preg_splits and whatnot.
function remove_words($str) {
$remove = array('SOMNAMBULIST', 'EREGO', 'HERETOFORE');
$patterns = array();
foreach($remove as $rm) {
$patterns[] = '/(^|\s)' . preg_quote($rm) . '($|\s)/i';
}
return preg_replace($patterns, '', $str);
} // remove_words()
echo "'" . remove_words('I think erego I am') . "'<br>"; // needs a space!
echo "'" . remove_words('Heretofore unknown') . "'<br>"; // works great