php聊天功能逻辑原理,@xxx提及用户,这种功能的实现原理是怎样的?
12
2014-12-13 22:05:54 +08:00 ? 1
在牛客網(wǎng) http://www.nowcoder.com 用戶在我們網(wǎng)站提交的評(píng)論,我們會(huì)進(jìn)行敏感詞過(guò)濾,其算法是基于有限狀態(tài)機(jī)DFA過(guò)濾的。 我覺(jué)得可以用敏感詞過(guò)濾的方法來(lái)查找@的用戶ID。 (用戶ID就是好多敏感詞), 具體的代碼如下:
/**
* 過(guò)濾敏感詞
*
* @param text
* @return
*/
public String filter(String text) {
if (StringUtils.isBlank(text)) {
return text;
}
String replacement = DEFAULT_REPLACEMENT;
StringBuilder result = new StringBuilder();
DFATreeNode tempNode = rootNode;
int begin = 0; // 回滾數(shù)
int position = 0; // 當(dāng)前比較的位置
while (position < text.length()) {
char c = text.charAt(position);
// 空格直接跳過(guò)
if (isSymbol(c)) {
++position;
continue;
}
tempNode = tempNode.getSubNode(c);
// 當(dāng)前位置的匹配結(jié)束
if (tempNode == null) {
// 以begin開(kāi)始的字符串不存在敏感詞
result.append(text.charAt(begin));
// 跳到下一個(gè)字符開(kāi)始測(cè)試
position = begin + 1;
begin = position;
// 回到樹(shù)初始節(jié)點(diǎn)
tempNode = rootNode;
} else if (tempNode.isKeywordEnd()) {
// 發(fā)現(xiàn)敏感詞, 從begin到position的位置用replacement替換掉
result.append(replacement);
position = position + 1;
begin = position;
tempNode = rootNode;
} else {
++position;
}
}
result.append(text.substring(begin));
return result.toString();
}
總結(jié)
以上是生活随笔為你收集整理的php聊天功能逻辑原理,@xxx提及用户,这种功能的实现原理是怎样的?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 手机两列布局,正方形
- 下一篇: PHP程序中时间戳,php 时间戳常用代