我有一个匹配错误单词的功能。我希望得到匹配的词。
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;
}
如何将匹配的单词存储在创建语句列“单词”中
答案 0 :(得分:1)
我认为最好的解决方案是让函数在发现任何单词时返回单词,而在没有发现任何单词时返回null。
private function match($needles, $haystack)
{
foreach ($needles as $needle) {
if (strpos($haystack, $needle) !== false) {
return $needle;
}
}
}
现在,您可以使用if语句检查是否返回了单词:
$word = $this->match($forbiddenPhrases, $thought_content)
if ($word) {
Flagable::create(['status' => '2', 'word' => $word, 'word_id' => '']);
}
答案 1 :(得分:0)
像这样更改您的功能:
private function match($needles, $haystack){
foreach($needles as $needle){
if (strpos($haystack, $needle) !== false) {
return needle;
}
}
return false;
}
,然后像这样更改您的代码:
Public function store(PostRequest $request){
$post = Post::create($request->validated());
$warningWords = Word::where('type', 'warning_words')->pluck('content')->toArray();
if(($word = $this->match($forbiddenPhrases, $thought_content)) !== false){
Flagable::create('status' => '2', 'word' => $word, 'word_id' => '']);
}
}
答案 2 :(得分:0)
/**
* Checks and returns all forbiddenPhrases found in the content
*
* @param array $forbiddenPhrases
* @param string $content
*
* @return array
*/
private function match(array $forbiddenPhrases, string $content){
$content = strtolower($content);
$forbiddenPhrases = array_map('strtolower', $forbiddenPhrases);
return array_filter($forbiddenPhrases, function($word){
return str_contains($content, $word);
});
}
然后在控制器中可以执行以下操作:
$forbiddenPhrases = Word::where('type', 'warning_words')->pluck('content', 'id')->toArray();
$foundForbiddenPhrases = $this->match($forbiddenPhrases, $content);
if(count($foundForbiddenPhrases) > 0){
foreach ($foundForbiddenPhrases as $phraseId => $foundForbiddenPhrase) {
Flagable::create('status' => '2', 'word' => $foundForbiddenPhrase, 'word_id' => $phraseId]);
}
}