doubeijian2257
doubeijian2257
2013-02-14 12:24
浏览 72
已采纳

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

I want to make it so that when I type in for example "hello i hope you have a good day bye" it will only highlight 'hello' and 'bye'. How would I go about doing this?

Because at the moment it currently highlights with yellow the whole line, which isn't what I want.

Here is my code below:

<?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>';
?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • doubomudichen0832
    doubomudichen0832 2013-02-14 12:27
    已采纳
    <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;
    ?>
    
    点赞 评论
  • duanou9739
    duanou9739 2013-02-14 12:26

    Yes, this approach is plausible, but font html tag IS obsolete, use span instead.

    点赞 评论
  • duanmei1930
    duanmei1930 2013-02-14 12:28

    Try something like this:

    <?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;
    }
    

    This would put a yellow background colour around "hello" and "bye" in the output.

    点赞 评论
  • douhan9619
    douhan9619 2013-02-14 12:37

    Your problem

    Your last line, the one that is echoing your result is wrong as you wrap your whole sentence in an highlighting context (<font> tag).

    Solution

    1. You need to parse your original sentence ;
    2. wrap your keywords in an highlighting context.

    You can do this in the preg_replace() function. I would also recommend the use of the <mark> tag whom goal is to indicate relevance in context.

    Code

    <?php 
    $original_sentence = $_POST['words'];
    $highlight_sentence = $original_sentence; 
    $word_to_highlight = array('Hello', 'Bye'); // list of words to highlight
    
    foreach ($word_to_highlight as $word) {
      $pattern = printf('/\b%s\b/i', $word); // match a different word at each step
      $replace_by = printf('<mark>%s</mark>', $word); // replacement is updated at each step
      $highlight_sentence = preg_replace($pattern, $replace_by, $words);
    }
    ?>
    
    <style type="text/css">
    mark {
       background: #ffc;
    }
    </style>
    
    点赞 评论

相关推荐