我正在尝试编写一个PHP脚本,它将文本作为输入,浏览整个文本(例如它可以是一篇很长的文章),然后搜索字形式的用户输入。在文本中搜索一个单词并突出显示它
它应该打印出用户正在搜索的高亮显示字词的全文,无论它在哪里找到。
<!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>
你错过了,我说的注释:“波纹管只是一些应该解释什么,我试图做的,我知道,这个代码将不能像这样的工作。” –
我正在尝试打印整个文本,并在该文本中搜索词的每个实例都应该突出显示。 解析错误不是问题。 ( - 1)+ 6 –
你刚刚通过代码快速,没有看到我实际上正在尝试做什么 –