如何在php中仅更改部分文本?

如何在php中仅更改部分文本?,php,Php,我有一个php代码,可以在文本中搜索数据库中的单词并突出显示它们: <?php if(isset($_POST['submit'])){ $text = $_POST['search']; $text2 = preg_replace("#[[:punct:]]#", "", $text); $words = explode(&quo

我有一个php代码,可以在文本中搜索数据库中的单词并突出显示它们:

<?php
            if(isset($_POST['submit'])){
                $text = $_POST['search'];
                $text2 = preg_replace("#[[:punct:]]#", "", $text);
                $words = explode(" ", $text2);
                $count = count($words);
                for ($i=0; $i<$count-1; $i++){
                    $word = $words[$i];
                    $word = trim($word);
                    $word1 = $words[$i+1];
                    $word2 = $word . ' ' . $word1;
                    $query = "SELECT * FROM ta WHERE name = '$word2'";
                    $result = mysqli_query($connect, $query); 
                    $row = mysqli_fetch_array($result);
                    $word3 = $row['name'];
                    if (!empty($word3)) {
                        $text2 = str_replace($word3, "<span style='color:rgb(252, 127, 3);' class='mytext'>$word3</span>", $text);
                    }
                }
                echo nl2br($text2);
            }
        ?>

如果在
If
中使用回音,它将
echo
all

$word3 = $row['name'];
if (!empty($word3)) {
$text2 = str_replace($word3, "<span style='color:rgb(252, 127, 3);' class='mytext'>$word3</span>", $text);
echo nl2br($text2);
}

str_replace
实际上会替换给定搜索字符串的所有实例。也许您正在寻找
stri\u replace
(以消除区分大小写)。请提供文本示例、要替换的单词、预期输出和实际输出。此外,请插入强制SQL注入警告。无论何时接受用户输入,请使用准备好的语句。将$text2转换为数组
$word3 = $row['name'];
if (!empty($word3)) {
$text2 = str_replace($word3, "<span style='color:rgb(252, 127, 3);' class='mytext'>$word3</span>", $text);
echo nl2br($text2);
}
$text2 = str_replace($word3, "<span style='color:rgb(252, 127, 3);' class='mytext'>$word3</span>", $text);
$text2Arr[]= $text2;