0

我有一个完整的 .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 和括号以仅检索文本行?
4

3 回答 3

2

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

$id = "07";
preg_match("/\[$id\] (.*)/", file_get_contents($file), $match);
echo $match[1];
  • 匹配[$id],然后是空格,然后匹配其他所有内容并捕获它(.*)
于 2019-09-19T14:11:06.730 回答
0

首先,我建议您使用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
于 2019-09-19T14:10:23.193 回答
-1
$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 包含输出

于 2019-09-19T14:11:58.433 回答