-4

If i have a text file that contain data of names:

John
Ham
Joe
Tope
Nalawas

i want php to look for Joe and remove it from the list. Any idea?

my idea:

<?php
$lines = file('user.txt');
$word = '';
$result = '';

foreach($lines as $line) {
    if(substr($line) == 'joe') {
        $result .= $word."\n";
    } else {
        $result .= $line;
    }
}

file_put_contents('user.txt', $result);

?>

this code is not working i want to use preg-replace

Alfred George
  • 126
  • 1
  • 8

2 Answers2

2

This works well.
But as mentioned will remove Joesephine, too

$lines  = file('names.txt');
$search = 'joe';

$result = '';
foreach($lines as $line) {
    if(stripos($line, $search) === false) {
        $result .= $line;
    }
}
file_put_contents('names2.txt', $result);
halojoy
  • 225
  • 2
  • 7
0

Just use $result = str_replace('Joe','',$line);

As a reminder this approach will work in the case you mentioned, but if there were names like "Joesephine" it would produce line: sephine

Also might want to check out: strtolower() when comparing strings like this to account for case-insensitivity http://php.net/manual/en/function.strtolower.php

user3647971
  • 1,069
  • 1
  • 6
  • 13