无法从字符串中删除破折号( - )

时间:2011-07-05 15:34:49

标签: php string preg-replace

以下函数将一些单词划分为一个数组,调整空格并执行我需要的其他操作。我还需要删除短划线,因为我也将它们写成单词。但是此功能不会删除短划线。怎么了?

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;

}

2 个答案:

答案 0 :(得分:1)

要回答您的问题,问题是指定字边界的\b。如果在连字符之前或之后有空格,则不会将其删除,如“ - ”中所示,单词边界不适用。

来自http://www.regular-expressions.info/wordboundaries.html

  

有三种不同的立场   有资格作为单词边界:

     
      
  1. 在第一个角色之前   string,如果第一个字符是a   字符。
  2.   
  3. 最后一次   字符串中的字符,如果是最后一个   字符是一个字符。
  4.   
  5. 之间   字符串中的两个字符,其中   一个是单词,另一个是单词   不是一个字符。
  6.         

    “单词字符”是可用于形成单词的字符。

一个简单的解决方案:

通过将\s\b添加到您的模式并使用积极的后视和积极的预测,您应该能够解决您的问题。

$pattern = '#(?<=\b|\s|\A)(' . join('|', $words) . ')(?=\b|\s|\Z)\s*#iS'; 

答案 1 :(得分:0)

你的正则表达式模式中没有找到破折号。为什么不做呢

$string = str_replace('-', '', $string);

你做了正则表达式的东西后?