Using preg_replace() to remove words from a string.
Posted: Tue May 18, 2004 3:09 pm
I am trying to remove whole words from a string. (I need to remove the word 'and' but not the substring 'and' of the word andy.) The below works but only 'and' is removed. Nothing else in the array $a_words_to_exclude is removed from the string.
I would like $searchVal to return the following:
'Additional coverages grey otto unavailable options andy some'
Code: Select all
<?php
$searchVal = 'Additional and coverages - grey otto unavailable options andy and on some';
$a_words_to_exclude = array('and','a','or','for','at','an', 'the', 'in', 'of','etc','is','to','-','if','do','on');
$needle = join('|',$a_words_to_exclude);
$searchVal = preg_replace("/\b($needle)\b/i","",$searchVal,-1);
//I have also tried:
//$searchVal = preg_replace("/($needle)/i","",$searchVal,-1);
?>'Additional coverages grey otto unavailable options andy some'