2010-08-14 115 views
1

这是来自大型文本文件的一些示例文本。PHP正则表达式替换计算

(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...', ...), 

现在我需要添加19到第一列的每个值...

(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()似乎是解决方案,但我真的不使用正则表达式...

回答

1
preg_replace_callback(
    '/(?<=\()(\d+)(?=,.+\),?\v)/', 
    function($match) { 
     return (string)($match[1]+19); 
    }, 
    $large_text 
); 
+0

非常感谢! (正则表达式让我有点头晕) – Glenn 2010-08-14 17:41:22

+0

但是,能否请你解释一下reg。你用过的表情? – Glenn 2010-08-14 17:47:52

+0

'(?<= \()'寻找一个主括号作为替换表达式开始的提示,但它不包含在要被替换的表达式中 - 但只有数字被'(\ d +)'表示。正则表达式的其余部分只是验证数字后面的逗号直到后面的括号,一个可选的逗号(如果它是最后一行),还有一个换行符或垂直空白符号,如'\ v'所示。(?=,。+ \),?\ v)'表示它不是要替换的表达式的一部分。 – stillstanding 2010-08-14 18:10:09

0

这会为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);