Laravel中如何将匹配到的违规词存入Flagable的word字段?
获取违规词匹配函数中具体匹配到的词汇
我现在有一个违规词匹配的函数,想把匹配到的具体词汇存到数据库里。现有代码如下:
Public function store(PostRequest $request){ $post = Post::create($request->validated()); $warningWords = Word::where('type', 'warning_words')->pluck('content')->toArray(); if($this->match($forbiddenPhrases, $thought_content)){ Flagable::create(['status' => '2', 'word' => '', 'word_id' => '']); } } private function match($needles, $haystack){ foreach($needles as $needle){ if (strpos($haystack, $needle) !== false) { return true; } } return false; }
请问怎么在Flagable::create()语句里,把匹配到的词汇存入word列?
解决方案
你的match函数目前只返回布尔值(匹配/不匹配),没法拿到具体的违规词。我们只需要调整这个函数的返回值,再在store方法里用返回的词汇填充字段就行,具体步骤如下:
1. 修改match函数,返回匹配到的具体词汇
把原来返回true的地方改成返回当前匹配到的$needle,没匹配到就返回null:
private function match($needles, $haystack){ foreach($needles as $needle){ if (strpos($haystack, $needle) !== false) { return $needle; // 返回匹配到的词汇,代替原来的true } } return null; // 无匹配时返回null }
2. 在store方法中获取匹配词并写入数据库
先调用match函数拿到结果,再判断是否创建Flagable记录。另外注意你代码里的变量名问题:$forbiddenPhrases应该是你定义的$warningWords,$thought_content要换成请求里对应的字段(比如$request->thought_content):
public function store(PostRequest $request){ $post = Post::create($request->validated()); $warningWords = Word::where('type', 'warning_words')->pluck('content')->toArray(); // 获取匹配到的违规词 $matchedWord = $this->match($warningWords, $request->thought_content); if($matchedWord){ // 顺便获取对应word的id(如果需要的话) $wordId = Word::where('type', 'warning_words') ->where('content', $matchedWord) ->value('id'); Flagable::create([ 'status' => '2', 'word' => $matchedWord, 'word_id' => $wordId ?? '' // 找不到id就存空字符串 ]); } }
额外需求:匹配所有违规词
如果你需要把内容中所有匹配到的违规词都记录下来,而不是只记录第一个,可以让match函数返回一个匹配数组:
private function match($needles, $haystack){ $matchedWords = []; foreach($needles as $needle){ if (strpos($haystack, $needle) !== false) { $matchedWords[] = $needle; } } return $matchedWords; }
然后在store方法中循环创建记录:
public function store(PostRequest $request){ $post = Post::create($request->validated()); $warningWords = Word::where('type', 'warning_words')->pluck('content')->toArray(); $matchedWords = $this->match($warningWords, $request->thought_content); if(!empty($matchedWords)){ foreach($matchedWords as $word){ $wordId = Word::where('type', 'warning_words') ->where('content', $word) ->value('id'); Flagable::create([ 'status' => '2', 'word' => $word, 'word_id' => $wordId ?? '' ]); } } }
内容的提问来源于stack exchange,提问作者user10928644
相关产品推荐
相关产品推荐

