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>';
?>
<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;
?>
Yes, this approach is plausible, but font
html tag IS obsolete, use span
instead.
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.
Your last line, the one that is echoing your result is wrong as you wrap your whole sentence in an highlighting context (<font>
tag).
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.
<?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>