无法从字符串中删除破折号(-) [英] Can't remove dashes (-) from string
本文介绍了无法从字符串中删除破折号(-)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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:
有三个不同的位置 符合单词边界条件的:
- 在第一个字符之前 字符串,如果第一个字符是 单词字符。
- 在最后一个之后 字符串中的字符,如果最后 字符是单词字符。
- 之间 字符串中的两个字符,其中 一个是单词字符,另一个是字符 不是单词字符。
"Word Character"是可用于构词的字符。
简单的解决方案:
将s
和一起添加到您的模式中,并使用积极的回顾和积极的展望,您应该能够解决您的问题。
$pattern = '#(?<=|s|A)(' . join('|', $words) . ')(?=|s|)s*#iS';
这篇关于无法从字符串中删除破折号(-)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文