2010-08-14 59 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);