当一个词只是一个词时,去掉一个词,而不是复合词的一部分 [英] strip a word when is a single word only, not part of a composite word

查看:45
本文介绍了当一个词只是一个词时,去掉一个词,而不是复合词的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下功能,我希望它在只有一个单词时去除alpha"而不是像alphadog"这样的复合词的一部分.现在我只看到狗",这不好.有什么帮助吗?

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: 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

推荐答案

这个:

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

应该是这样的:

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

这篇关于当一个词只是一个词时,去掉一个词,而不是复合词的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆