开发者

How do I edit this text file using PHP?

I do have a text file having around 400k data in it. and its content is like this..

开发者_运维问答
1,james
2,mathew
3,yancy
4,brandon
5,molner
6,nick
7,neil...and so on

How do I remove numbers and comas from this text file and keep only names?


Read the file into an array, where each array item is one line. Walk throught the array, find the first comma, and remove it and everything before. Then write it all back out again.

// Warning! Brain-compiled code ahead.

$arr = file('myfile.txt');
foreach ( $arr as &$val )
    $val = substr($val, strpos($val, ',') + 1);
file_put_contents('myoutfile.txt', implode(PHP_EOL, $arr));

Note - no error checking. If a line lacks a comma, or comma is the last character, chaos ensues.


400k isn't incredibly much, so you should get away with this (tested):

foreach (file($path) as $line)
    print preg_replace("~^[0-9]+\,(.*)~", "$1", $line);


Here is a perl one liner that do the job:

perl -i.save -pe 's/^\d+,//'  test.txt

The original file will be saved in test.txt.save


This is tested and will return it as a list but you can save it to a database if you want:

$file_path='my_file.txt';
$file_handler = fopen($file_path, 'rt');

$doc = fread($file_handler, filesize($file_path)+1);

$rows = explode("\n", $doc);
$rows_array = array();
foreach ($rows as $row) {
    $data = explode(",", $row);
        $return_array[] = $data[1];
}

//print_r($return_array);
    //you can save it to a db

echo '<ul>';
foreach($return_array as $value){
    echo '<li>'.$value.'</li>';
}   
echo '</ul>';
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜