Rossitten Rossitten - 19 days ago 11
PHP Question

Find all strings of a text that have XXX at the EOL

I have a text file with 700,000 lines of login attempts some of which are successful but mainly - not. Here is an example:

login attempt 2 to server IP as user_name - password failed
login attempt 3 to server IP as user_name - password failed
login attempt 4 to server IP as user_name - **successful**
login attempt 5 to server IP as user_name - password failed
login attempt 6 to server IP as user_name - **successful**


and so on. How can I delete all lines that do not end with 'successful" word?
pseud-ocode:


  1. convert all lines to separate arrays with each word as an array element

  2. to write something like this (pseudocode):

    while(line_number <= 700000) {

    $all_occurrences .= (end($array) == 'successful') ? whole_line : '';
    }



so only these will remain:

> login attempt 4 to server IP as user_name - **successful** login
> attempt 6 to server IP as user_name - **successful**


Any thoughts?

Thank you!

Answer

The best thing is to read the files line by line so you don't run into memory constraints.

Solution 1:

<?php

$if = '/tmp/login.attempts';
$of = '/tmp/login.attempts.purged';
$ifh = fopen($if, 'r');
$ofh = fopen($of, 'w');

while(($line = fgets($ifh)) !== false) {
    if(preg_match('/successful/', $line)) {
        fwrite($ofh, $line);
    }
}

fclose($ifh);
fclose($ofh);

?>

Or if you want to use arrays like your sudo code.

Solution 2:

<?php

$if = '/tmp/login.attempts';
$contents = file_get_contents($if);

$all_attempts = explode("\n", $contents);

$successful_attempts = array();

foreach($all_attempts as $attempt) {
    if(preg_match('/successful/', $attempt)) {
        $successful_attempts[] = sprintf("%s", $attempt);
    }
}

// The successful_attempts array contains all your entries
//print_r($successful_attempts);
?>
Comments