Search code examples
phphighlighting

How do I highlight replaced words in 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>';
?>

Solution

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