Skip to content
Advertisement

Delete specific characters in text-file php

I have a text like that :

 # GEMEL
 Eclipse:        ,frank,jean
 accueil:        ,eclipse,alex
 accueil:        eclipse,truc

I want to delete the , in front of frank or eclipse, it can be any word.

My idea is to check if with have a comma before Eclipse:, or accueil: and if with have one then we delete only the comma to have :

 # GEMEL
 Eclipse:        frank,jean
 accueil:        eclipse,alex
 accueil:        eclipse,truc

But how can we delete just one commat if she exist ?

I creat the line with :

if($fd = file($filename)){

    //1- on recupere les données transmise
    $data = fgets(STDIN);
    $chaine2 = explode(",", $data);
    $chaine = $chaine2[0];
    $user = ",".$chaine2[1]."n";

    //var_dump($fd);
    foreach ($fd as $key => $value) {
        if(preg_match('/'.$chaine.'/', $value)){
            $fd[$key] = rtrim($value, "nr").$user;
        }
    }
    file_put_contents($filename, $fd);
}

Advertisement

Answer

$data = file_get_contents($filename);
$data = preg_replace('/(:s*),/', '$1', $data);
file_put_contents($filename, $data);

The regular expression matches everything from the : to the ,. The parenthesized group matches the part of that before the comma. So we replace it with $ so that we keep everything except the comma.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement