【问题标题】:Get entire text line that starts with search pattern获取以搜索模式开头的整个文本行
【发布时间】:2019-09-19 14:02:39
【问题描述】:

我有一个 .txt 文件,里面有很多行,每行都以方括号中的唯一 ID 开头:

[13] Text text text text text text text
[23] Text text text text text text text
[65] Text text text text text text text
[07] Text text text text text text text 
[66] Text text text text text text text

我使用 php 打开并检索文本文件内容:

$file = 'path_to_file/file.txt';
$handle = fopen($file, "r");
$content = fread($handle, filesize($file));
fclose($handle);

$search_id = '[65]';

我现在希望在$content 中找到以我正在搜索的 id ($search_id) 开头的单行,并仅检索该行。方括号中的 id(后跟空格)将始终启动行。检索该行时,我希望将其去掉这个 id,因为我只需要没有 id 的文本行。

我的问题是:

  • 如何最有效地搜索此文件?(id 总是只会出现一次)
  • 如何收集包含搜索键的行?以及
  • 如何删除前导 id 和括号以仅检索文本行?

【问题讨论】:

  • 文件是经常变化还是静态的?
  • @vivek_23 它可能会不时手动更改。运行此 php 代码的页面应该在每次运行时简单地检索文本行
  • 好的,目标是快速搜索吗?
  • 如果你想快速检索,那么在你的数据库中使用 ID 列索引。如果您不喜欢 DB 方式,恐怕,逐行处理似乎是唯一的方式。

标签: php file search


【解决方案1】:

如果文件不是很大,并且您已经在阅读整个文件,则可以使用正则表达式:

$id = "07";
preg_match("/\[$id\] (.*)/", file_get_contents($file), $match);
echo $match[1];
  • 匹配[$id],然后是一个空格,然后匹配其他所有内容并捕获它(.*)

【讨论】:

  • 谢谢。似乎运作良好。该文件可能包含几百行。会不会有速度问题?
  • 不,即使是数千也应该没问题。你需要计时。
【解决方案2】:

首先,我建议你使用file 来获取一个包含文件行的数组:

$file = 'path_to_file/file.txt';

$search_id = '[65]';

$lines = file($file);

$text = $textWithSearchId = '';
foreach($lines as $line)
{
    if(strpos(trim($line), $search_id) === 0)
    {
        $text = trim(substr($line, strlen($search_id)));
        $textWithSearchId = $line;
    }
}
echo "$text<br />$textWithSearchId";

这是一个工作测试:

$lines = array();
$lines[] = "[13] Text 13 text text text text text text";
$lines[] = "[23] Text 23 text text text text text text";
$lines[] = "[65] Text 65 text text text text text text";
$lines[] = "[07] Text 07 text text text text text text";
$lines[] = "[66] Text 66 text text text text text text";

$search_id = '[65]';

$text = $textWithSearchId = '';
foreach($lines as $line)
{
    if(strpos(trim($line), $search_id) === 0)
    {
        $text = trim(substr($line, strlen($search_id)));
        $textWithSearchId = $line;
    }
}
echo "$text<br />$textWithSearchId";

输出:

Text 65 text text text text text text
[65] Text 65 text text text text text text

【讨论】:

  • 就文件读取而言,这似乎是最快的。
【解决方案3】:
$file = 'path_to_file/file.txt';
$handle = fopen($file, "r");
$content = fread($handle, filesize($file));
fclose($handle);
$arr = explode(PHP_EOL, $content);
$search_id = '[65]';
foreach ($arr as $value) {
    $result = substr($value, 0, 4);
    if($result === $search_id) 
    {
      $string = str_replace($search_id,'', $value);
      print_r($string);
      return;
    }
}

变量 $string 包含输出

【讨论】:

  • 查看我的编辑建议;)(ps。我没有投反对票)
  • 我也没有投反对票,但可能是因为它只是一个没有解释的代码转储。
  • 好的,但我试图涵盖所有我已经更新代码的senerio 请检查
  • 你拒绝了我的编辑...查看它并添加一些文本来解释你的代码,这样做可能会很好
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-21
  • 1970-01-01
  • 1970-01-01
  • 2015-06-04
相关资源
最近更新 更多