1

我有这个txt文件结构:

"data";"data";"data";#;"my data";"my data";"my data"
"data";"data";"data";#;"my data";"my data";"my data"
"data";"data";"data";#;"my data";"my data";"my data"

我需要在 # 符号之后读取此文件数据。我的 PHP 代码只是为了阅读整行。

$file_handle = fopen("texto.txt", "r");
$numlinha = 0;
while (!feof($file_handle)) {
   $line = fgets($file_handle);
   $numlinha++;
   echo $numlinha . ". " . $line . "</br></br>";
}
fclose($file_handle);
4

4 回答 4

1

您可以使用strpos函数来查找第一个 # 字符在您的行中的位置。

$file_handle = fopen("texto.txt", "r");
$numlinha = 0;
while (!feof($file_handle)) {
   $line = fgets($file_handle);
   $cpos = strpos($line, '#');
   if ($cpos !== FALSE) {
       $line = substr($line, 0, $cpos);
   }
   $numlinha++;
   echo $numlinha . ". " . $line . "</br></br>";
}
fclose($file_handle);
于 2011-06-20T15:19:50.160 回答
1
$file_handle = fopen("texto.txt", "r");
$numlinha = 0;
while (!feof($file_handle)) {
   $line = fgets($file_handle);
   $parts = explode("#", $line);
   $parts[0] // part before the # in this line
   $parts[1] // part behind the # in this line
   $numlinha++;
   echo $numlinha . ". " . $line . "</br></br>";
}
fclose($file_handle);
于 2011-06-20T15:20:03.850 回答
1

您可以使用: $data = explode(";#;", $line); 然后对 $data[1] 而不是 $line 进行处理。

这假设 ;#; 每一行都是独一无二的...

请注意,我相信使用字符串位置测试 (strpos()) 和 substr() 来提取字符串的一部分会消耗更多资源,而不是仅仅使用您已经阅读的行并将其拆分为确切的已知分隔符,其中这种情况是;#;。

发布的其他示例假定 # 将仅在该行上出现一次,或者至少该分隔将是该行中的第一个 #。使用 ;#; 会使它更加独特,如果您需要将结果分解为其他用途的值数组,则可以通过 str_getcsv() 函数处理您的结果。

于 2011-06-20T15:22:59.570 回答
1

您可以使用explode函数,使用“#”分隔符将字符串分成两部分

http://php.net/function.explode

于 2011-06-20T15:24:08.670 回答