我有以下代码行来查找行号和行号。我的顶部有搜索栏的html表。首先,我想在此html表中显示所有行及其行号。然后根据搜索过滤器,相关的行号和行号将显示在该表中。我目前无法显示所有线条。但是,当我从搜索栏传递任何值时,它会显示过滤结果。
当我的$ str是“Adobe”时,它生成包含该单词的行号以及包含该给定单词的整行。现在我要找的是显示表格中的所有行和行号,并根据搜索过滤行。
任何人都可以通过以下行帮助我如何显示给定文件的所有行及其行号。
<?php include 'file.php';?>
<div class="container">
<div class="row">
<input type="text" id="myInput" placeholder="Search for names..">
<input type="button" name="view" value="View" class="btn-View">
</div>
<div class="row">
<table>
<?php foreach($arr as $ar){
?>
<tr>
<td width="8%"><?php echo $ar['line_number'];?></td>
<td width="92%"><?php echo $ar['line'];?></td>
</tr>
<?php }?>
</table>
</div>
</div>
file.php
$file = "file/file.txt";
$str = "Adobe";
$arr = count_line_no($file, $str);
function count_line_no($file, $str)
{
$arr_lines = array();
$handle = fopen($file, "r");
if ($handle) {
$count = 0;
$arr = array();
while (($line = fgets($handle)) !== false) {
$count+=1;
if (strpos($line, $str) !== false) {
$arr_lines['line'] = $line;
$arr_lines['line_number'] = $count;
array_push($arr, $arr_lines);
}
}
}
return $arr;
}
答案 0 :(得分:1)
function findLines($file,$str,$start=1,$limit=false){
$handle = fopen($file, "r");
if ($handle) {
$lineNo= 0;
$matches=0;
$arr = array();
while (($line = fgets($handle)) !== false) {
$lineNo++;
if (empty($str) || strpos($line, $str) !== false) {
$matches++;
//continue loop if we haven't reached our start point
if($matches<$start){
continue;
}
$arr_lines=[];
$arr_lines['line'] = $line;
$arr_lines['line_number'] = $lineNo;
$arr[] = ['line'=>$line,'line_number'=>$lineNo];
}
//stop when we have read the maximum number of lines
if($limit!==false && $matches>=($start+$limit)){
break;
}
}
}
return $arr;
}
这支持空白搜索和分页:
$arr = findLines($file, $str);
$arr = findLines($file, $str,10,10);
从页码编号:
$page=2;
$perPage=10;
$start = ($perPage)*$page-1;
$arr = findLines($file, $str,$start,$perPage);
答案 1 :(得分:0)
<?php
$file = "file/file.txt";
$str = "Adobe";
$arr = count_line_no($file, $str);
print_r($arr);
function count_line_no($file, $str)
{
$arr_lines = array();
$handle = fopen($file, "r");
if ($handle) {
$count = 0;
$arr = array();
while (($line = fgets($handle)) !== false) {
$count+=1;
if (strpos($line, $str) !== false) {
$arr_lines[]=array('line' => $line,"line_number"=>$count);
}
}
}
return $arr_lines;
}
输出格式:
Array
(
[0] => Array
(
[line] => Adobe
[line_number] => 4
)
[1] => Array
(
[line] => Adobe
[line_number] => 11
)
)
答案 2 :(得分:0)
我添加了这些行。
if(empty($str)){
$arr_lines[]=array('line' => $line,"line_number"=>$count);
}else{
if (strpos($line, $str) !== false) {
$arr_lines[]=array('line' => $line,"line_number"=>$count);
}
}
这是正确的方法吗?