如何在PHP中突出显示替换的单词?

如何在PHP中突出显示替换的单词?,php,highlighting,Php,Highlighting,我希望这样,当我输入例如“你好,我希望你有一个良好的一天再见”时,它只会突出显示“你好”和“再见”。我该怎么做呢 因为现在它用黄色突出显示了整条线,这不是我想要的 下面是我的代码: <?php $words = $_POST['words']; $words = preg_replace('/\bHello\b/i', 'Bonjour', $words); $words = preg_replace('/\bbye\b/i', 'aurevoir', $words); echo '<

我希望这样,当我输入例如“你好,我希望你有一个良好的一天再见”时,它只会突出显示“你好”和“再见”。我该怎么做呢

因为现在它用黄色突出显示了整条线,这不是我想要的

下面是我的代码:

<?php
$words = $_POST['words'];
$words = preg_replace('/\bHello\b/i', 'Bonjour', $words);
$words = preg_replace('/\bbye\b/i', 'aurevoir', $words);
echo '<FONT style="BACKGROUND-COLOR: yellow">'.$words.'</font>';
?>
<?php
$words = $_POST['words'];
$words = str_replace("hello", "<span class=\"highlight\">hello</span>", $words);
$wirds = str_replace("bye", "<span class=\"highlight\">bye</span>", $words);

print($words);

?>

// CSS FILE
.highlight {
    background-color: yellow;
}

是的,这种方法是合理的,但是
font
html标记已经过时,请改用
span

是的,这种方法是合理的,但是
font
html标记已经过时,请改用
span


<style type="text/css">
.highlight {
   background: yellow;
}
</style>
<?php
$words = $_POST['words'];
$words = str_ireplace('Hello', '<span class="highlight">Bonjour</span>', $words);
$words = str_ireplace('bye', '<span class="highlight">aurevoir</span>', $words);
echo $words;
?>
.亮点{ 背景:黄色; }

.亮点{
背景:黄色;
}

试试这样的方法:

<?php
$words = $_POST['words'];
$words = preg_replace('/\bHello\b/i', 'Bonjour', $words);
$words = preg_replace('/\bbye\b/i', 'aurevoir', $words);
echo '<FONT style="BACKGROUND-COLOR: yellow">'.$words.'</font>';
?>
<?php
$words = $_POST['words'];
$words = str_replace("hello", "<span class=\"highlight\">hello</span>", $words);
$wirds = str_replace("bye", "<span class=\"highlight\">bye</span>", $words);

print($words);

?>

// CSS FILE
.highlight {
    background-color: yellow;
}

//CSS文件
.亮点{
背景颜色:黄色;
}

这将在输出中的“hello”和“bye”周围放置一个黄色背景色。

尝试以下操作:

<?php
$words = $_POST['words'];
$words = preg_replace('/\bHello\b/i', 'Bonjour', $words);
$words = preg_replace('/\bbye\b/i', 'aurevoir', $words);
echo '<FONT style="BACKGROUND-COLOR: yellow">'.$words.'</font>';
?>
<?php
$words = $_POST['words'];
$words = str_replace("hello", "<span class=\"highlight\">hello</span>", $words);
$wirds = str_replace("bye", "<span class=\"highlight\">bye</span>", $words);

print($words);

?>

// CSS FILE
.highlight {
    background-color: yellow;
}

//CSS文件
.亮点{
背景颜色:黄色;
}
这将在输出中的“hello”和“bye”周围添加黄色背景色。

您的问题 您的最后一行,即与您的结果相呼应的那一行是错误的,因为您将整个句子包装在突出显示的上下文中(
标记)

解决方案
  • 你需要分析你原来的句子
  • 将关键字包装在突出显示的上下文中
  • 您可以在
    preg\u replace()
    函数中执行此操作。我还建议使用WHO来表示上下文中的相关性

    密码
    
    标记{
    背景:#ffc;
    }
    
    您的问题 您的最后一行,即与您的结果相呼应的那一行是错误的,因为您将整个句子包装在突出显示的上下文中(
    标记)

    解决方案
  • 你需要分析你原来的句子
  • 将关键字包装在突出显示的上下文中
  • 您可以在
    preg\u replace()
    函数中执行此操作。我还建议使用WHO来表示上下文中的相关性

    密码
    
    标记{
    背景:#ffc;
    }
    
    是的,此回复合理,但此处的答案不合适,请使用注释。是的,此回复合理,但此处的答案不合适,请使用注释。注意,如下所示,在进行简单文本替换时,应使用str\u ireplace而不是preg\u replace.note,如下所示,在进行简单文本替换时,应使用str_ireplace而不是preg_replace。