I am trying to write a php script that takes a text as an input, goes through the whole text (for example it can be a very long essay), and search for the word user inputs in the form.
It should print out the whole text with the highlighted word user was searching for, wherever it was found.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Search for a word in text</title>
</head>
<body>
<form method="post" action="index.php">
<input type="text" name="text" placeholder="Insert the text you want to search in...">
<input type="text" name="find_x" placeholder="Insert the word you want to find...">
<input type="submit" value="Search">
</form>
<?php
// this just prints out a line used to devide input area from a result
$line = "<br>" . str_repeat("___", 40) . "<br></br>";
echo $line;
if ( isset($_POST["text"]) and !empty($_POST["text"]) and
isset($_POST["find_x"]) and !empty($_POST["find_x"]) )
{
$text = $_POST["text"];
$find_x = $_POST["find_x"];
// transforms inputs to lowercase so the word is found even if written in uppercase
$text_lc = strtolower($text);
$find_x_lc = strtolower($find_x);
// find length of searched word
$length_of_x = strlen($find_x_lc);
// variable for offsetting
$offset = 0;
// prints out all starting positions of a searched word
while ( $position_in_text = strpos($text_lc, $find_x_lc, $offset) )
{
echo "The string <b><u>$find_x</u></b> is found in your text and it is at position $position_in_text" . "<br>";
$offset = $position_in_text + $length_of_x;
}
// here I want to print the whole text, and wherever the searched word appears in the text it should be highlighted (bold or underlined). I don't know how to do that!?
}
?>
</body>