本文介绍了无法从字符串中删除破折号(-)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的函数将一些单词剥离到一个数组中,调整空格并执行我需要的其他操作。我还需要去掉破折号,因为我也把它们写成单词。但此函数不会删除破折号。怎么了?

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 = '#(' . join('|', $words) . ')s*#iS';
  }

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

}

推荐答案

要回答您的问题,问题是,它指定了一个词边界。如果在连字符前面或后面有空格,则不会像在"-"中那样删除它,因此不适用单词边界。

发件人http://www.regular-expressions.info/wordboundaries.html

简单的解决方案:

s一起添加到您的模式中,并使用积极的回顾和积极的展望,您应该能够解决您的问题。

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

这篇关于无法从字符串中删除破折号(-)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-26 07:21