[英]how to bring back filtered rows in an html table using PHP (no MySQL)
在我的html中,我有一個搜索功能,當單擊“提交”按鈕時,運行了一個PHP功能,該功能應篩選出不包含搜索到的單詞的行,而僅過濾HTML表中包含搜索到的單詞的行,頁。 我的HTML表是使用PHP生成的,該PHP正在從.txt文件中讀取書籍。 我的代碼從文本文件中帶回行,而不是過濾表結果。 有什么幫助嗎?
的HTML
<form action="search.php" method="POST">
<p>Enter Word to Search</p>
<p>
<input type="text" name="search_term"/>
<input type="submit" value="Search"/>
</form>
的PHP
$search_term = $_POST['search_term'];
foreach($books as $book){
$book_formatted = str_replace('|', '', $book);
$pos = stripos($book_formatted, $search_term);
if($pos === false){
print "Not found";
}else{
$book_formatted = substr($book_formatted, 0, $pos);
$book_formatted = trim($book_formatted);
$pos2 = stripos($book_formatted, $search_term);
if($pos2 === false){
print "Not found in the list";
}else{
print "Titles that match: ". $book_formatted;
}
}
}
如果沒有真正看到$books
甚至$book
樣子,似乎每個搜索都會因此而失敗:
$book_formatted = substr($book_formatted, 0, $pos);
如果您的書是“ ABC書”,而您的搜索是“ Bo”,則第一個條紋會給您結果4,這不是錯誤的,因此移至您的else部分。 但是,然后您再次對書名進行子字符串化,將名稱砍成“ ABC”,然后再次搜索“ Bo”,這通常會失敗。
也許您正在嘗試獲取搜索詞及其后的所有內容? 在這種情況下,只需使用
$book_formatted = substr($book_formatted, $pos);
這將返回“書”。 在這種情況下,第二次搜索是無意義的,因為它總是返回0。除非未提供更多內容,否則只要您按自己的意願格式化書名並在第一個else語句中打印而不是第二次打印就可以了脫衣舞。
編輯:
在頁面上的某處,您可能有一個循環打印表行:
foreach($books as $book){
...
print "<tr><td>" . $book . "</td></tr>";
...
}
基本上像這樣將所有代碼復制到該打印行周圍的循環中
$search_term = $_POST['search_term'];
...
// this should be the loop on your page that is printing the contents of the table
foreach($books as $book){
...
$book_formatted = str_replace('|', '', $book);
$pos = stripos($book_formatted, $search_term);
if($search_term == "" || $pos !== false) {
// this should be whatever line, or group of lines, that is printing the table rows
print "<tr><td>" . $book_formatted. "</td></tr>";
}
}
重要的是要注意,搜索位置僅在$ search_term不為空時才重要,這樣,如果不進行搜索,將顯示所有行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.