我正在嘗試編寫一個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 –
你剛剛通過代碼快速,沒有看到我實際上正在嘗試做什麼 –