开发者

How can I read a text file with 200 lines of text, and identify identical string values?

I have a text file that contains 200 lines of text. How can I compare each line of text and identify the same values with PHP. Is that even possible? Can I convert the lines to XML fo开发者_如何学JAVArmat? Can I convert the text file to HTML and append the duplicate values to an un-ordered list?


Are you looking to make an array of duplicate lines? If so, you could use something like this:

<?php

/* load the file as an array of lines */
$lines = file('myfile');

/* put them in sorted order */
sort($lines);

/* loop over each line comparing it to the previous, to determine if it is a dup */
$last_line = null;
$duplicates = array();
foreach ($lines as $line)
{
  /* only add it to the duplicates array if it is not already there */
  if (strcmp($line, $last_line) == 0 && ! in_array($line, $duplicates))
  {
    $duplicates[] = $line;
  }
  $last_line = $line;
}

/* view the duplicates */
var_dump($duplicates);
?>


I'll answer you one question, first: Yes, you can. I'm tired so I'll sholl you just messy and unusable code in production case

$lines = file("file.txt");
sort($lines);

foreach ($lines as $line)
{
    if (in_array($line, $lines) && !in_array($line, $dupes))
    {
       $dupes[] = $line;
    }
}

print_r($dupes);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜