首页 > 解决方案 > php从数据库表中查找和替换文本中的单词

问题描述

我正在做一个项目。它在给定文本中搜索并替换数据库中的单词。在数据库中有 10k 个单词和替换。所以我想搜索每个单词并替换这个单词的替换词。

顺便说一句,我正在使用laravel。我只需要替换的想法。

我尝试了一些方法,但它只替换了一个词。

我的数据库表结构如下;

id词替换

1 测试测试

ETC

文本来自输入,替换后,我想在结果页面中显示哪些单词被替换为不同的 bg 颜色。

我试过下面的代码工作正常,但它只替换了一个词。

    $article = trim(strip_tags($request->article));
    $clean = preg_split('/[\s]+/', $article);
    $word_count = count($clean);
    $words_from_database_for_search = Words::all();
    foreach($words_from_database_for_search as $word){
        $content = str_replace($word['word'],
            "<span class=\"badge badge-success\">$word[replacement] 
    </span>",
            $article);
    }
    $new_content = $content ;
    $new_content_clean = preg_split('/[\s]+/', $new_content);
    $new_content_word_count= count($new_content_clean);

编辑,

我使用 preg_replace 而不是 str_replace。我得到它的工作,但这次我想显示有多少单词改变了,所以我试图从替换后的文本中找到改变的单词数。算错了。

例如,如果有 6 个更改,则显示 3 或 4

它可以通过 preg_replace_callback 完成,但我之前没有使用过,所以我不知道如何弄清楚;我的工作代码如下;

    $old_article = trim(strip_tags($request->article));
    $old_article_word_count = count($old_article );
    $words_from_database_array= Words::all();
    $article_will_replace = trim(strip_tags($request->article));
    $count_the_replaced_words = 0;
    foreach($words_from_database_array as $word){

        $article_will_replace = preg_replace('/[^a-zA- 
    ZğüşıöçĞÜŞİÖÇ]\b'.$word['word'].'\b\s/u',
            " <b>".$word['spin']."</b> ",
            $article_will_replace );

        $count_the_replaced_words = preg_match_all('/[^a-zA- 
ZğüşıöçĞÜŞİÖÇ]\b'.strip_tags($word['spin']).'\b\s/u',$article_will_replace 
     );
        if($count_the_replaced_words ){

            $count_the_replaced_words ++;

        }



    }

标签: phpstringreplace

解决方案


我很困惑,你不需要<?php ... ?>$word[replacement] 周围的东西吗?

    foreach($words_from_database_for_search as $word){
        $content = str_replace($word['word'],
            "<span class=\"badge badge-success\"><?PHP $word[replacement] ?> 
    </span>",
            $article);
    }

然后将其移入for循环并在等号前添加一个点:

$new_content .= $content ;

推荐阅读