Podolski
Podolski

Reputation: 85

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

Upvotes: 1

Views: 197

Answers (4)

djjjuk
djjjuk

Reputation: 358

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

Upvotes: 2

&#201;douard Lopez
&#201;douard Lopez

Reputation: 43401

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>

Upvotes: 1

EM-Creations
EM-Creations

Reputation: 4301

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.

Upvotes: 1

Bud Damyanov
Bud Damyanov

Reputation: 31879

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

Upvotes: 0

Related Questions