Re: preg_replace problem

From: Date: Thu, 02 Mar 2006 02:07:06 +0000
Subject: Re: preg_replace problem
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-231310@lists.php.net to get a copy of this message
Is there any special reason why you want to solve this with regular expressions? As far as I see, there's a couple of problems with your code, a) $file = dog.txt should be $file = 'dog.txt', b) $getOldValue has the _array_ resulting of parsing the INI file, hence you should write $getOldValue, since it's the complete file (I won't say anything about performance), c) you're using a regular expresion to increment the value in a specific key/index, and you don't need regexp for that, and d) you're not saving the whole file, only the "setting" (entry) for "today", hence you overwrite the file and leave only "today = n" What do you think of something like this (a bit changed):
    $file        = 'dog.txt';
    $today       = date("Ymd");
    // we read the file,
    $getOldValue = parse_ini_file($file);
    // set or increment the value in "$today" key,
@$getOldValue[$today] ++;
    // and write back the whole INI file
    // note: what we have is an array, not a string
    $str_ini = '';
    foreach ( $getOldValue as $date => $value ) {
        $str_ini .= "$date = $value\n";
    }
    file_put_contents($file, $str_ini);
Benjamin Adams wrote:
$file = dog.txt; $today = date("Ymd"); function incDate($new, $date){
        //$date = settype('int');
        return $new.($date++);
} $getOldValue = parse_ini_file($file, 1); $newValue = $getOldValue[$today] + 1; $oldDate = $today . " = ". $newValue; $newDate = preg_replace('/(\d+\s\=\s)(\d+)/ie', 'incDate("$1","$2")', $oldDate); file_put_contents($file, $newDate . "\n"); This works with one file but with multi lines I'm having trouble: if the file has: 20060301 = 34 20060302 = 3 the file after script will be: 20060302 = 4 I want it to preserve the previous lines so output should be: 20060301 = 34 20060302 = 4 Help would be great, thanks Ben -- Atentamente, J. Rafael Salazar Magaña Innox - Innovación Inteligente Tel: +52 (33) 3615 5348 ext. 205 / 01 800 2-SOFTWARE http://www.innox.com.mx


« previous php.general (#231310) next »