Question

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, "\n\r").$user;
        }
    }
    file_put_contents($filename, $fd);
}
Was it helpful?

Solution

$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.

OTHER TIPS

if ($fd = file($filename)) {
    foreach ($fd as $key => $value) {
        $fd[$key] = preg_replace('/(\s+),/', '$1', $value));
    }
    file_put_contents($filename, $fd);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top