strip a word when is a single word only, not part

2019-07-28 17:21发布

I have the following function, I want it to strip "alpha" when is a single word only and not a part of a composite word like "alphadog". Now instead I just see "dog" and it's not good. Any help?

    function stripwords($string) 
{ 
  // build pattern once 
  static $pattern = null; 
  if ($pattern === null) { 
    // pull words to remove from somewhere 
    $words = array('alpha', 'beta', '-');  
    // escape special characters 
    foreach ($words as &$word) { 
      $word = preg_quote($word, '#'); 
    } 
    // combine to regex 
    $pattern = '#\b(' . join('|', $words) . ')\b\s*#iS'; 
  } 

  $print = preg_replace($pattern, '', $string);
  list($firstpart)=explode('+', $print);
  return $firstpart;

}

edit: hi, i have another problem... i've edited above with the new version of the function: it strips words, adjust whitespaces and then does something else i need, but it doesn't remove dashes (or minus)... what's wrong? i tried something but no avail...thanks

2条回答
仙女界的扛把子
2楼-- · 2019-07-28 17:31

This:

$pattern = '#' . join('|', $words) . '#iS';

Should be this:

$pattern = '#\b' . join('\b|\b', $words) . '\b#iS';
查看更多
Lonely孤独者°
3楼-- · 2019-07-28 17:41

Use this regexp pattern

/\balpha\b/

\b stands for "word boundary", it means it will match the word by separate (if the word is surrounded by word separators).

Hope this helps

查看更多
登录 后发表回答