开发者

How do I find the line in a text file beginning with 5678 and replace it with nothing using php?

Lets say the text file contains:

56715:Jim:12/22/10:19  
5678:Sara:9/04/08:92    
53676:Mark:12/19/10:6  
56797:Mike:12/04/10:123  
5678:Sara:12/09/10:49  
56479:Sammy:12/12/10:645  
56580:Martha:12/19/10:952  

I would like to find the lines b开发者_开发知识库eginning with "5678" and replace them with nothing, so the file will now contain only:

56715:Jim:12/22/10:19  
53676:Mark:12/19/10:6  
56797:Mike:12/04/10:123  
56479:Sammy:12/12/10:645  
56580:Martha:12/19/10:952 

Thanks.


// The filename
$filename = 'filename.txt';

// Stores each line into an array item
$array = file($filename);

// Function to return true when a line does not start with 5678
function filter_start($item)
{
   return !preg_match('/^5678:/', $item);
}

// Runs the array through the filter function
$new_array = array_filter($array, 'filter_start');

// Writes the changes back to the file
file_put_contents($filename, implode($new_array));


Well, just use preg_replace:

$data = file_get_contents($filename);
$data = preg_replace('/^5678.*(\n|$)/m', '', $data);

Note the m modifier. That puts PCRE into multiline mode, where ^ matches the start of the document, and after any new-line character (and $ matches the end of the document, and before any new-line character)...

Also, depending on your exact needs, you could create a stream filter:

class LineStartFilter extends php_user_filter {
    protected $data = '';
    protected $regex = '//';
    public function filter($in, $out, &$consumed, $closing) {
        var_dump($this->regex);
        while ($bucket = stream_bucket_make_writeable($in)) {
            $bucket->data = preg_replace($this->regex, '', $bucket->data);
            $consumed += $bucket->datalen;
            stream_bucket_append($out, $bucket);
        }
        return PSFS_PASS_ON;
    }
    public function onCreate() {
        list($prefix, $data) = explode('.', $this->filtername);
        $this->data = $data;
        $this->regex = '/^'.preg_quote($data, '/').'.*(\n|$)/m';
    }
}
stream_filter_register('linestartfilter.*', 'LineStartFilter');

Then, just do this when you want to read the file:

$f = fopen('test.txt', 'r');
stream_filter_append($f, 'linestartfilter.5678');
fpassthru($f);
fclose($f);

That will output your requested string. And if you want to write to another file (copy it):

$f = fopen('test.txt', 'r');
stream_filter_append($f, 'linestartfilter.5678');
$dest = fopen('destination.txt', 'w');
stream_copy_to_stream($f, $dest);
fclose($f);
fclose($dest);


preg_replace('~5678:[^\n]+?\n~', '', $text);

If your text ends with \n, otherwise convert the line endings first.


Tim Cooper just reminded me what file() does :)

$lines = file($filename);

$lines = preg_grep('/^5678/', $lines, PREG_GREP_INVERT);

$file = implode($lines);

file_put_contents($filename, $file);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜