我想从字符串中删除一些特定的单词和短语,然后我在Strip specific words from string进行了讨论。
我创建了一系列禁用词: $ wordlist = array(" bayes"," full","大于");
我的示例字符串是:
$string= "my bayesian results are full of bayes and greater than anything else";
如果我应用以下代码:
foreach ($wordlist as &$word) {
$word = '/\b' . preg_quote($word, '/') . '\b/';
}
$string = preg_replace($wordlist, '', $string);
结果是: 我的贝叶斯结果比其他任何东西都要大[删除单词:贝叶斯,全部]
而我想要的结果是: 我的结果是和其他任何东西[删除单词:贝叶斯,贝叶斯,完整,大于]
请注意,我希望禁词“贝叶斯”#39;应该删除“贝叶斯”这个词。同样。
答案 0 :(得分:1)
尝试在结束边界之前添加.*?
。它会非贪婪地匹配,直到到达边界。
就像这样 -
$word = '/\b' . preg_quote($word, '/') . '.*?\b/';
^^^
输出 -
my results are of and anything else
答案 1 :(得分:0)
也许这个:
$string = "my bayesian results are full of bayes and greater than anything else";
$forbidden = array('/bayes(\w+)/','/full(\w+)/');
$result = preg_replace($forbidden , array(), $string);
print_r($result);
此代码获取字符串,尝试将一组正则表达式模式($ forbidden)与字符串匹配,并用空值替换它们。
它查找以bayes或full开头的单词,并在找到空格时停止查找。
答案 2 :(得分:0)
首先将字符串拆分为单词,然后针对每个被禁止的单词检查每个单词,并在必要时将其删除。
$string = "my bayesian results are full of bayes and greater than anything else";
$banned_words = array("bayes", "full", "greater than");
$words = explode(' ',$string);
foreach($words as $key => $word) {
foreach($banned_words as $banned_word) {
if(false !== stripos($word,$banned_word)) {
unset($words[$key]);
break;
}
}
}
$string = implode(' ',$words);
最后删除任何1+单词完整匹配
print str_ireplace($banned_words,'',$string);