tags:

views:

37

answers:

2

This is some sample text from a large text file.

(2, 1, 3, 2, 'text...','other text...', 'more text...', ... ),
(3, 1, 3, 2, 'text...','other text...', 'more text...', ... ),
(4, 1, 3, 2, 'text...','other text...', 'more text...', ... ),
(5, 1, 3, 2, 'text...','other text...', 'more text...', ... ),
(6, 1, 3, 2, 'text...','other text...', 'more text...', ... ), 

Now I need to to add 19 to each value of the first column...

(21, 1, 3, 2, 'text...','other text...', 'more text...', ... ),
(22, 1, 3, 2, 'text...','other text...', 'more text...', ... ),
(23, 1, 3, 2, 'text...','other text...', 'more text...', ... ),
(24, 1, 3, 2, 'text...','other text...', 'more text...', ... ),
(25, 1, 3, 2, 'text...','other text...', 'more text...', ... ), 

preg_replace_callback() seems the solution, but I'm not really used to regular expressions...

+1  A: 
preg_replace_callback(
    '/(?<=\()(\d+)(?=,.+\),?\v)/',
    function($match) {
        return (string)($match[1]+19);
    },
    $large_text
);
stillstanding
Thanks a lot!! (regular expressions make me a bit dizzy)
Glenn
But could you please explain the reg. expression you used?
Glenn
`(?<=\()` looks for a leading parenthesis as the cue for the start of the expression to replace but it's not included in the expression to be replaced - but only digits as signified by `(\d+)`. The rest of the regex just verifies that a comma after the digits is present up to to trailing parentheses, an optional comma (in case it's the last line), and a line break, or vertical whitespace, as signified by the `\v`. `(?=,.+\),?\v)` means it's not part of the expression to replace.
stillstanding
A: 

This would do it for stdin.

// Your function
function add19($line) {
    $line = preg_replace_callback(
        '/^\(([^,]*),/',
        create_function(
            // single quotes are essential here,
            // or alternative escape all $ as \$
            '$matches',
            'return ("(" . (intval($matches[1])+19) . ",");'
        ),
        $line
    );
    return $line;
}

// Example reading from stdin
$fp = fopen("php://stdin", "r") or die("can't read stdin");
while (!feof($fp)) {
    $line = add19(fgets($fp));
    echo $line;
}
fclose($fp);
LatinSuD