开发者

PHP for read txt file line just upon sign "#"

I have this txt file structure:

"data";"data";"data";#;"my data";"my data";"my data"
"开发者_StackOverflow社区data";"data";"data";#;"my data";"my data";"my data"
"data";"data";"data";#;"my data";"my data";"my data"

I need to read this file data just after the # sign. My PHP code just for read the entire line.

$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);


You can use strpos function to find position of first # char in your line.

$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);


$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);


You could use: $data = explode(";#;", $line); And then do your processing on $data[1] instead of $line.

This assumes that ;#; is unique on each line...

Note that using string position testing (strpos()) and substr() to extract the part of the string would be more resource consuming, I believe, than just taking the line you already read and splitting it at the exact known delimiter, which in this case is ;#;.

The other examples posted assume that # will be only on the line once, or at least the divide will be the first # in the line. Using ;#; would make it more unique, and your result can be processed by the str_getcsv() function if you needed to break it down into an array of values for other uses.


You can use the explode function, to split the string in two parts using the "#" delimiter

http://php.net/function.explode

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜